验证使用Moq调用的泛型方法

时间:2013-02-27 23:55:57

标签: c# moq verify

我无法验证是否使用IInterface.SomeMethod<T>(T arg)调用了Moq.Mock.Verify的模拟。

我可以使用It.IsAny<IGenericInterface>()It.IsAny<ConcreteImplementationOfIGenericInterface>()验证是否在“标准”界面上调用了该方法,并且我没有使用It.IsAny<ConcreteImplementationOfIGenericInterface>()验证通用方法调用的麻烦,但是我无法验证使用It.IsAny<IGenericInterface>()调用泛型方法 - 它始终表示该方法未被调用且单元测试失败。

这是我的单元测试:

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());
}

这是我的课程:

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);
    }
}

这是我的IServiceInterface

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

这是我的接口/类继承层次结构:

public interface ISpecificCommand
{
}

public class ConcreteSpecificCommand : ISpecificCommand
{
}

2 个答案:

答案 0 :(得分:6)

这是Moq 4.0.10827中的一个已知问题,它是当前版本。请参阅GitHub上的讨论https://github.com/Moq/moq4/pull/25。我已经下载了它的dev分支,编译并引用它,现在你的测试通过。

答案 1 :(得分:0)

我准备好了。由于GenericMethod<T>要求提供T参数,是否可以这样做:

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