How to make fun of SendGrid

I am trying to write a unit test for a method that I wrote that sends an email with SendGrid. My method looks something like this:

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 is a property that is set in my constructor through a parameter so that I can create a layout.

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

In my testing method, I am trying to make fun of the TransportWeb property (of type 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());
    }

However, I get the following error:

Incorrect setting for a non-virtual (redefined in VB) element: x => x.DeliverAsync

Does anyone have an idea how I can fix this?

+4
source share
1 answer

Ok, I fixed it :)

Web, ITransport:

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

var em = new EmailManager(transport.Object);

, Simon V.

+4

Source: https://habr.com/ru/post/1546670/


All Articles