To mock a protected virtual (non-generic) method in Moq is easy:
public class MyClass
{
....
protected virtual int MyMethod(Data data){..}
}
And to mock it:
myMock.Protected().Setup<int>("MyMethod", ItExpr.Is<Data>( ...
I could not find a way to use the same technique if the protected method is generic, like:
protected virtual int MyMethod<T>(T data)
Any idea how to do it, besides using a wrapper class to override that method, is highly appreciated.
I've checked the source and it seems mocking protected generic methods with Moq is not supported:
The Protected()
method creates an instance of a class ProtectedMock<T>
which uses the following method to get the method that you want to mock:
private static MethodInfo GetMethod(string methodName, params object[] args)
{
return typeof(T).GetMethod(
methodName,
BindingFlags.Instance | BindingFlags.NonPublic | BindingFlags.Public,
null,
ToArgTypes(args),
null);
}
It uses Type.GetMethod to get the method for mocking, but GetMethod
(although MSDN states differently) don't play nice with generics, see:
GetMethod for generic method
Get a generic method without using GetMethods
Side note: In my opinion mocking a protected member is a code smell, and I would rather try to avoid it anyway with refactoring my design (beside that it's not supported in Moq).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With