如何模拟SendGrid

时间:2014-07-01 11:19:40

标签: c# unit-testing moq mstest sendgrid

我正在尝试为我编写的方法编写单元测试,该方法使用SendGrid发送电子邮件。 我的方法是这样的:

public async Task SendEmail(TemplatedMailMessage emailMessage)
{
    if (String.IsNullOrWhiteSpace(emailMessage.Html) || String.IsNullOrWhiteSpace(emailMessage.From.ToString()) || !emailMessage.To.Any())
    {
        throw new Exception("Html, From or To is empty");
    }

    try
    {
        // Send the email
        await this.TransportWeb.DeliverAsync(emailMessage.GetSendGridMessage());
    }
    catch (Exception ex)
    {
        //do stuff
    }

    //log success
}

TransportWeb是一个通过参数在我的构造函数中设置的属性,因此我可以创建一个模拟对象。

public EmailManager(Web transportWeb = null)
{
    this.TransportWeb = transportWeb ?? SetupSendGrid();
}

在我的测试方法中,我试图模拟TransportWeb(类型为SendGrid.Web)属性:

    [TestMethod]
    public async Task SendEmail_ValidEmailTemplateAndNoParameters_EmailIsSent()
    {
        //ARRANGE
        var templatedMailmessage = new Mock<TemplatedMailMessage>();
        var transportWeb = new Mock<Web>();
        transportWeb.SetupAllProperties();
        transportWeb.Setup(x => x.DeliverAsync(It.IsAny<ISendGrid>()));
        var emailManager = new EmailManager(transportWeb.Object);

        //ACT
        await emailManager.Send(templatedMailmessage.Object);

        //ASSERT
        transportWeb.Verify(x => x.DeliverAsync(It.IsAny<ISendGrid>()), Times.Once());
    }

但是,我收到以下错误:

  

非虚拟(VB中可覆盖)成员的设置无效:x =&gt;   x.DeliverAsync

有人知道如何解决这个问题吗?

1 个答案:

答案 0 :(得分:5)

好的我修好了它:)

您不应该使用Web类,而是使用ITransport接口:

var transport = new Mock<ITransport>();
transport.SetupAllProperties();
transport.Setup(x => x.DeliverAsync(It.IsAny<SendGridMessage>())).ReturnsTask();

var em = new EmailManager(transport.Object);

我还使用了extensions methods创建的Simon V