Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mocking a protected generic method with Moq

Tags:

moq

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.

like image 855
Sunny Milenov Avatar asked Feb 23 '12 15:02

Sunny Milenov


1 Answers

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

like image 72
nemesv Avatar answered Sep 20 '22 16:09

nemesv