c# - 验证使用 Moq 调用的通用方法

标签 c# moq verify

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

我可以使用 It.IsAny<IGenericInterface>() 验证该方法是在“标准”接口(interface)上调用的或 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());
}

这是我正在测试的类(class):

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

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

public interface ISpecificCommand
{
}

public class ConcreteSpecificCommand : ISpecificCommand
{
}

最佳答案

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

关于c# - 验证使用 Moq 调用的通用方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15124934/

相关文章:

c# - Xamarin:在android中加载布局axml文件时出错

c# - 使用最小起订量验证某些方法的不同参数的多次调用

c# - Moq 是单元测试的代理

linux - 如何强制 rpm -V 验证所有文件?

text - 如何使用 selenium IDE 验证是否存在任何文本

java - 验证月份输入 01 和 1?

c# - 如果宏位于工作表中,无法通过互操作运行宏吗?

c# - 如何更改 RichTextBox 文本内容中特定单词(或短语)的颜色

c# - 具有基于角色授权的 ASP.NET Web Api

c# - 如何使用内部构造函数模拟事件