How to divert “non public” method in public class moles
-
25-10-2019 - |
문제
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.
해결책 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.
다른 팁
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.