I am trying to write a unit test for a method I wrote which sends out an email with SendGrid. My method is 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
}
the TransportWeb is a property which is set in my constructor through a parameter so I can create a mock object.
public EmailManager(Web transportWeb = null)
{
    this.TransportWeb = transportWeb ?? SetupSendGrid();
}
In my test method I am trying to mock the TransportWeb (of type SendGrid.Web) property:
    [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:
Invalid setup on a non-virtual (overridable in VB) member: x => x.DeliverAsync
Does anybody have an idea how I can fix this?
Okay I fixed it :)
You should not use the Web class but ITransport interface:
var transport = new Mock<ITransport>();
transport.SetupAllProperties();
transport.Setup(x => x.DeliverAsync(It.IsAny<SendGridMessage>())).ReturnsTask();
var em = new EmailManager(transport.Object);
I also used the extensions methods created by Simon V.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With