Verifying generic method called using Moq

梦想与她 提交于 2019-12-01 14:54:00

问题


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
{
}

回答1:


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.




回答2:


I'm going to wing it. Since GenericMethod<T> requires that a T argument be provided, would it be possible to do:

mockInterface.Verify(serviceInterface => serviceInterface.GenericMethod(It.Is<object>(x=> typeof(ISpecificCommand).IsAssignableFrom(x.GetType()))), Times.Once());


来源:https://stackoverflow.com/questions/15124934/verifying-generic-method-called-using-moq

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!