My class and method that mocks:
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);
}
}
And unit test for it
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("[email protected]", "SenderDemo", "Ilya", "EmailServiceUnitTest", "Demo", "Test",
"<strong>Hello</strong>");
Assert.Equal(1, test);
}
And the problem is that my mock does not rise my callback method
Probably the issue because of async nature of the method that mocks, but I really need some your help :)
You are mocking
SendEmailAsync(new SendGridMessage(), CancellationToken.None)
But calling
_client.SendEmailAsync(msg)
So which one is the right one? Also you don't need this test
variable. Simply use
mockEmailClient.Verify(x => x.SendEmailAsync(...), Times.Once)
You could actually write it this way:
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("[email protected]", "SenderDemo", "Ilya", "EmailServiceUnitTest", "Demo", "Test",
"<strong>Hello</strong>");
mockEmailClient.Verify(x => x.SendEmailAsync(It.IsAny<YourMessageType>()), Times.Once);
}
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