0

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 = "kumara@gmail.com";
            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");
            
        }
Kumara
  • 1
  • 1

1 Answers1

1

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.

  1. Do you want to test the SendEmail method and make sure the subject, message and etc are correct when sending the object to _emailService?
  2. Do you want to test the actual sending email implementation and expect the email to be delivered to your Gmail account? This is not a good practice for unit tests because your tests rely on many external setups.

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.

Charles Han
  • 1,920
  • 2
  • 10
  • 19