Question

I have a public method that uses a local private method to get data from the Db.

private string SomeMethod(string) { ... Doing some operations ... string data = GetDBData(string); Doing some operations ... }

I want to divert/isolate the private method GetDBData(string) using moles so my test will not require the DB.

Obviously, my question is: how to do it? thank you Uria

EDIT
Additional information:

i tried to change the method accessors both to public and internal protected, in both cases i can now see the methods as moles. BUT when running the test, the original method is still being used and not the detour I've implemented in the PexMethod.

Was it helpful?

Solution 2

I figured it out

If i have the public MyClass with private SomeMethod

public class MyClass
{
    private string SomeMethod(string str){}
}

if you want to mole the SomeMethod method you need to use AllInstances in the test method:

[PexMethod]
SomeMethod(string str)
{
    MMyClass.AllInstances.SomeMethod = (instance, str) => { return "A return string"; };
}
  • notice that the lambda receives an instance parameter as the first parameter. I'm not sure what it's function is.

OTHER TIPS

You can try any of the following.

  • Make the method internal and add an attribute like this to the assembly:

    [assembly: InternalsVisibleTo("<corresponding-moles-assembly-name>")]

  • Change the method access to protected virtual and then use a stub.

  • Refactor your class so that it gets an interface (IDataAccessObject) as a constructor parameter, SomeMethod being one of the methods of that interface, and then pass a stub of that interface to your class in test methods.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top