Quick Tips For Creating Email Templates in Test Methods

First up, there's been some radio silence here and for that I apologise, Proximity Insight has suddenly gotten very busy and on top of that my daughter was born; turns out babies are a lot more work than coding, and infinitely harder to debug.

Anyway, to the point. Sending emails from Apex isn't particularly uncommon, but it turns out testing such methods can prove a little tricky. Weirdly with the latest release I'm not seeing any issues in actually invoking the Messaging.sendEmail() method itself, but I was finding it hard to create an email template to use.

Creating Test Data

First of all there's the usual DML issues with setup & non-setup objects: I needed to create a Contact and an EmailTemplate record, and this will normally throw an error. This can be circumvented by using System.runAs(), and the best bit is you don't even need to create a new User to use that method:

User thisUser = [select Id from User where Id = :UserInfo.getUserId()]; 

System.runAs(thisUser)  
{ 
    // insert setup objects here 
}
// insert regular objects here 

Creating a Template

I played around for some time trying to insert an HTML or Visualforce template (for starters you need to create LetterHead data and that can't be DML'd it seems), but since you can't test the result of sending it seemed like a lot of hard work for no real gain. In the end I settled for creating an empty text template instead. Sure, tests should check for outcomes, but if the Salesforce HTML/Visualforce email rendering engine ever breaks I'm pretty sure a few people will notice and have it fixed rather rapidly.

EmailTemplate et = testTemplate = new EmailTemplate();  
et.isActive = true;  
et.Name = 'testTemplate';  
et.DeveloperName = 'testTemplate' + System.now().getTime();  
et.TemplateType = 'text';  
et.FolderId = UserInfo.getUserId();  
et.Body = ''; 

insert et;  

I'm a advocate for writing proper tests, but there are occasions on the fringes of the platform where you simply have to let go of your ideals just to maintain your sanity, and testing these was one such occasion. There's nothing ground breaking here, I just wanted to put this together because I figured it'd be of use to others (or maybe just myself) in the future. If you have any other tips for testing email sending I'd love to hear them!

comments powered by Disqus