Moq:验证是否在没有实际执行代码的情况下调用了void

时间:2014-01-07 21:17:04

标签: moq

我有以下类,我想用Moq测试一个方法:

public class TestClass: ITestClass
{
        // ...
    public void ProcessAutomaticFillRequest(FillRequestParamDataContract fillRequestParam)
    {
        //...

        NotificationServer.Instance.Publish(channel, fillRequestParam);
    }

在我的测试中,我有以下内容:

    [TestMethod]
    public void CanFillRequest()
    {
        // ...

        _notificationServer.Setup(ns => ns.Publish(It.IsAny<string>(), It.IsAny<FillRequestParamDataContract>())).Verifiable();
        _TestClass.ProcessAutomaticFillRequest(fillRequestParam);
        _notificationServer.Verify(ns => ns.Publish(It.IsAny<string>(), It.IsAny<FillRequestParamDataContract>()), Times.Once);
    }

问题是我想测试是否调用了Publish但是没有在Publish方法中实际运行代码,因为它有太多依赖,我无法模拟。我认为使用Verifiable()可以做到这一点,但我得到了依赖项抛出的异常。我想要做的就是测试是否完成了对Publish的调用,但是在测试期间没有运行它的代码。

1 个答案:

答案 0 :(得分:0)

您必须为其传递NotificationServer实例才能调用mocked方法,否则它将调用NotificationServer.Instance返回的实例的方法。像下面的东西应该工作。如果有意义的话,你也可以在构造函数中传递实例。

[TestMethod]
public void CanFillRequest()
{
    var _notificationServer = new Mock<NotificationServer>();
    _TestClass.ProcessAutomaticFillRequest(fillRequestParam, _notificationServer.Object);

// Below change "string" to whatever the type for channel is.
    _notificationServer.Verify(ns => ns.Publish(It.IsAny<string>(), It.IsAny<FillRequestParamDataContract>()), Times.Once);
}

public class TestClass : ITestClass
{
    // ...
    public void ProcessAutomaticFillRequest(FillRequestParamDataContract fillRequestParam, NotificationServer _notificationServer)
    {
        //...

        _notificationServer.Publish(channel, fillRequestParam);
    }
}