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

Verify failing with default / expected parameters

任何人都可以帮助解决以下失败的代码。据我所知,我不知道为什么我列出的预期参数不会导致方法触发。

测试代码:

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)

您需要在执行测试后verify/assert:

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

.Verify() 是一种在 之后 调用的方法,实际上是为了 验证 您所使用的方法重新建议调用。