最低订量回调不会调用我已设置的最低订量

时间:2018-07-10 12:07:09

标签: c# .net unit-testing moq

我模拟的类和方法:

public class EmailService: IEmailService
{
    private readonly ISendGridClient _client;

    public EmailService(ISendGridClient client)
    {
        _client = client;
    }

    public async Task SendAsync(string email, string senderAderess, string senderName, string recipientName, string subject, string content, string htmlContent)
    {
        var from = new EmailAddress(senderAderess, senderName);
        var to = new EmailAddress(email, recipientName);
        var plainContent = content;
        var msg = MailHelper.CreateSingleEmail(from, to, subject, plainContent, htmlContent);

        await _client.SendEmailAsync(msg);
    }
}

并对其进行单元测试

public async void EmailService_SendingEmail_EmailSentSuccessfullyAsync()
{
    var test = 0;

    var mockEmailClient = new Mock<ISendGridClient>();

    mockEmailClient.Setup(x => x.SendEmailAsync(new SendGridMessage(), CancellationToken.None)).Callback(() => test++);

    var emailSender = new EmailService(mockEmailClient.Object);

    await emailSender.SendAsync("mail@gmail.com", "SenderDemo", "Ilya", "EmailServiceUnitTest", "Demo", "Test",
            "<strong>Hello</strong>");

    Assert.Equal(1, test);
}

问题是我的模拟程序没有使用我的回调方法

可能是由于模拟方法的异步性质造成的,但我确实需要您的帮助:)

2 个答案:

答案 0 :(得分:1)

您在嘲笑

SendEmailAsync(new SendGridMessage(), CancellationToken.None)

但是打电话

_client.SendEmailAsync(msg) 

那么哪一个是正确的呢?另外,您不需要此test变量。只需使用

 mockEmailClient.Verify(x => x.SendEmailAsync(...), Times.Once)

您实际上可以这样写:

   public async Task EmailService_SendingEmail_EmailSentSuccessfullyAsync()
    {
        var mockEmailClient = new Mock<ISendGridClient>();

        mockEmailClient.Setup(x => x.SendEmailAsync(It.IsAny<YourMessageType>()));

        var emailSender = new EmailService(mockEmailClient.Object);

        await emailSender.SendAsync("mail@gmail.com", "SenderDemo", "Ilya", "EmailServiceUnitTest", "Demo", "Test",
            "<strong>Hello</strong>");

        mockEmailClient.Verify(x => x.SendEmailAsync(It.IsAny<YourMessageType>()), Times.Once);
    }

答案 1 :(得分:0)

模拟的客户端需要返回完整的Task,以允许异步流继续进行。

这将允许在执行测试时调用回叫。

public async Task EmailService_SendingEmail_EmailSentSuccessfullyAsync() {
    //Arrange
    var test = 0;

    var mockEmailClient = new Mock<ISendGridClient>();

    mockEmailClient
        .Setup(x => x.SendEmailAsync(It.IsAny<SendGridMessage>(), It.IsAny<CancellationToken>()))
        .Returns(Task.FromResult((object)null)) //<-- needed to allow async flow to continue
        .Callback(() => test++);

    var emailSender = new EmailService(mockEmailClient.Object);

    //Act    
    await emailSender.SendAsync("mail@gmail.com", "SenderDemo", "Ilya", "EmailServiceUnitTest", "Demo", "Test",
            "<strong>Hello</strong>");

    //Assert    
    Assert.Equal(1, test);
}

还请注意对测试的更改以及用于设置模拟的参数匹配器