Unit testing code that sends email

When sending email through Apex, is not very clear how you should be building the unit test for it, as emails are not actually sent through unit tests. So I was wondering about this and found some information that I believe can be helpful to other to properly write unit test for a method that sends emails.
Let’s think on the following class:

public with sharing class EmailUtility 
{
	public static void sendPlainTextEmail(List<String> toAddresses, String subject, String body)
	{    	
    	Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.settoAddresses(toAddresses);
		mail.setSubject(subject);
		mail.setPlainTextBody(body);
		Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
	}
}

Basically in here we are encapsulating the functionality to send an email using Messaging.sendEmail. So the question now comes in how should we test this?
There are some interesting System methods that provide information on the governor limits at that particular moment. In this case we are going to be using Limits.getEmailInvocations()
So the test class looks like the following:

@isTest
private class EmailUtilityTest 
{
    @isTest
    static void testEmailUtility()
    {
        Test.StartTest();
        EmailUtility.sendPlainTextEmail(new List<String>{'test@test.com'}, 'Unit Test X', 'Unit Test');
        Integer invocations = Limits.getEmailInvocations();
        Test.stopTest();

        System.assertEquals(1, invocations, 'An email has not been sent');
    }
}

By using this, we can validate that the email was sent, even under a testing transaction.

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s