Search code examples
unit-testingmolespex

How to divert "non public" method in public class moles


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.


Solution

  • 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.