使用默认/预期参数验证失败

时间:2015-06-16 14:50:19

标签: c# moq

任何人都可以帮助解决以下代码,这是失败的。从我所看到的,我无法说明为什么列出的预期参数不会导致该方法触发。

测试代码:

Mock<ExpiryNotifier> target = new Mock<ExpiryNotifier>();
Mock<MailServiceWrapper> mailMock = new Mock<MailServiceWrapper>();
mailMock.Verify(
    m => m.SendMail(
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string[]>(),
        It.IsAny<string[]>(),
        It.IsAny<string[]>(),
        It.IsAny<string>(),
        It.IsAny<string>(),
        It.IsAny<string[]>()
    ), 
    Times.Exactly(1)
);
target.Setup(t => t.getMailService()).Returns(mailMock.Object);
target.Object.notify();

实际代码:

public virtual MailServiceWrapper getMailService()
{
    MailServiceWrapper MailService = new MailServiceWrapper();
    return MailService;
}

public string notify()
{
    string feed = loadFeed();
    MailServiceWrapper MailService = getMailService();
    MailService.SendMail(
                "sysmail.blah.net",
                "blah@blah.com",
                new string[] {"blah@blah.com"},
                new string[] { },
                new string[] { },
                "blah blah",
                "This is a blah blah email",
                new string[] { }
            );
}

方法签名:

public virtual string SendMail(string server, string from, string[] to, string[] ccs, string[] bccs, string title, string body, string[] attachments)

2 个答案:

答案 0 :(得分:3)

您需要在执行测试后验证/断言:

// Arrange
Mock<ExpiryNotifier> target = new Mock<ExpiryNotifier>();
Mock<MailServiceWrapper> mailMock = new Mock<MailServiceWrapper>();
target.Setup(t => t.getMailService()).Returns(mailMock.Object);

// Act
target.Object.notify();

// Assert
mailMock.Verify(
            m => m.SendMail(
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<string[]>(),
                It.IsAny<string[]>(),
                It.IsAny<string[]>(),
                It.IsAny<string>(),
                It.IsAny<string>(),
                It.IsAny<string[]>()
            ), 
            Times.Exactly(1)
        );

答案 1 :(得分:0)

.Verify()是一种在之后被称为的方法,以便验证您所建议的方法 调用。