Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Verifying generic method called using Moq

Tags:

c#

moq

verify

I'm having trouble verifying that mock of IInterface.SomeMethod<T>(T arg) was called using Moq.Mock.Verify.

I'm can verify that method was called on a "Standard" interface either using It.IsAny<IGenericInterface>() or It.IsAny<ConcreteImplementationOfIGenericInterface>(), and I have no troubles verifying a generic method call using It.IsAny<ConcreteImplementationOfIGenericInterface>(), but I can't verify a generic method was called using It.IsAny<IGenericInterface>() - it always says that the method was not called and the unit test fails.

Here is my unit test:

public void TestMethod1()
{
    var mockInterface = new Mock<IServiceInterface>();

    var classUnderTest = new ClassUnderTest(mockInterface.Object);

    classUnderTest.Run();

    // next three lines are fine and pass the unit tests
    mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once());
    mockInterface.Verify(serviceInterface => serviceInterface.NotGenericMethod(It.IsAny<ISpecificCommand>()), Times.Once());
    mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ConcreteSpecificCommand>()), Times.Once());

    // this line breaks: "Expected invocation on the mock once, but was 0 times"
    mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.IsAny<ISpecificCommand>()), Times.Once());
}

Here is my class under test:

public class ClassUnderTest
{
    private IServiceInterface _service;

    public ClassUnderTest(IServiceInterface service)
    {
        _service = service;
    }

    public void Run()
    {
        var command = new ConcreteSpecificCommand();
        _service.GenericMethod(command);
        _service.NotGenericMethod(command);
    }
}

Here is my IServiceInterface:

public interface IServiceInterface
{
    void NotGenericMethod(ISpecificCommand command);
    void GenericMethod<T>(T command);
}

And here is my interface/class inheritance hierarchy:

public interface ISpecificCommand
{
}

public class ConcreteSpecificCommand : ISpecificCommand
{
}
like image 942
sennett Avatar asked Feb 27 '13 23:02

sennett


1 Answers

It is a known issue in the Moq 4.0.10827 which is a current release version. See this discussion at GitHub https://github.com/Moq/moq4/pull/25. I have downloaded its dev branch, compiled and referenced it and now your test passes.

like image 51
Dmitriy Melnik Avatar answered Oct 14 '22 02:10

Dmitriy Melnik