I have a method to send an email. How can I write a unit test to verify this method. I'm using MS test with shouldly
public async Task SendEmail(string Id, string exception)
{
SendEmailModel sendEmailmodel = new SendEmailModel();
var emailAddress = _emailConfiguration.ToEmailAddress;
string[] toAddresses = emailAddress.Split(',', 10, StringSplitOptions.RemoveEmptyEntries);
sendEmailmodel.Subject = "Subject";
sendEmailmodel.ToAddresses = toAddresses;
sendEmailmodel.Message = exception;
await _emailService.SendEmailAsync(sendEmailmodel);
}
I tried writing test method as follows
[TestMethod]
public async Task SendEmail_should_send_email()
{
SendEmailModel sendEmailmodel = new SendEmailModel();
var emailAddress = "[email protected]";
string[] toAddresses = emailAddress.Split(',', 10, StringSplitOptions.RemoveEmptyEntries);
sendEmailmodel.Subject = "HA test email";
sendEmailmodel.ToAddresses = toAddresses;
sendEmailmodel.Message = "test";
await emailService.SendEmailAsync(sendEmailmodel);
A.CallTo(() => this.emailService.SendEmailAsync(sendEmailmodel));
//how to assert
await this.limitsLogic.SendEmail("120", "test");
}
Without showing your classes and the code structure, it's a bit hard to suggest a solution (my comments will be based on some assumptions).
The first thing I will do is defining the scope of the unit test.
For the first case, you can mock the external services using Moq to mock _emailConfiguration and _emailService, assuming that the two services are injected. Then in your unit test, you can provide mocked configurations and verify that the _emailService can receive a correct send mail model.
For the second case, you probably want to create an integration test where you can call Gmail API and get the expected email.