Search code examples
c#moq

Mocking generic method call for any given type parameter


I have an interface

public interface IDataProvider
{
    T GetDataDocument<T>(Guid document) where T:class, new()
}

I'd like to mock it in a way, that it would just return a new instance of a given type, regardless of the exact type, something like:

myMock.Setup(m => m.GetDataDocument<It.IsAny<Type>()>(It.IsAny<Guid>()))
.Returns(() => new T());

(which doesn't work of course, because I cannot just give any type parameter to moq, and I can't know which type must be returned.

Any ideas on this one?


Solution

  • Instead of using a mock, maybe your case would be better to use a Stub.

    public class StubDataProvider : IDataProvider
    {
        public T GetDataDocument<T>(Guid document) where T : class, new()
        {
            return new T();
        }
    }
    

    If you truly need a mock (so you can verify that GetDataDocument was called). Instead of trying to wrestle with a Mocking framework it sometimes is easier to just create a Mock class out right.

    public class MockDataProvider : IDataProvider
    {
        private readonly Action _action;
    
        public MockDataProvider(Action action)
        {
            _action = action;
        }
    
        public T GetDataDocument<T>(Guid document) where T : class, new()
        {
            _action();
            return new T();
        }
    }
    

    And than in your test:

    bool wasCalled = false;
    IDataProvider dataProvider = new MockDataProvider(() => { wasCalled = true; });
    var aTable = dataProvider.GetDataDocument<ATable>(new Guid());
    Debug.Assert(wasCalled);