验证使用Moq调用的通用方法 [英] Verifying generic method called using Moq

查看:89
本文介绍了验证使用Moq调用的通用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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

我可以使用It.IsAny<IGenericInterface>()It.IsAny<ConcreteImplementationOfIGenericInterface>()验证是否在标准"接口上调用了该方法,并且可以使用It.IsAny<ConcreteImplementationOfIGenericInterface>()验证通用方法调用没有任何麻烦,但是我无法验证通用方法是使用It.IsAny<IGenericInterface>()调用的-它始终表示未调用该方法,并且单元测试失败.

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.

这是我的单元测试:

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

这是我的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
{
}

推荐答案

这是Moq 4.0.10827(当前版本)中的一个已知问题.在GitHub https://github.com/Moq/moq4/pull/25.我已经下载了它的dev分支,对其进行了编译和引用,现在您的测试通过了.

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.

这篇关于验证使用Moq调用的通用方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆