Test before insert on Case created from Email-to-Case

before-triggeremail2caseunit-test

Background: I have a method that runs in before insert context on Cases. It looks for Cases that were created via standard Email-to-Case functionality when sent to a specific routing address. It parses out some of the info from the text body of the email and populates Case field values based on that info.

Problem: I'm struggling with how to get this covered in a test class. I want to mimic the Email-to-Case functionality to create the Case, as my code queries info from the EmailMessage object to match it to the correct Case and then set the Case field values.

TL;DR: How can I, in a test class, send an email to a specified address and have it create a Case via standard Email-to-Case?

Best Answer

To test email-to-case in a testmethod, you simulate what Email-to-Case (E2C) does.

Thus, in your testmethod:

// Given a Case as if inserted by E2C
Case e2cCase = new Case(
                   Description = 'the body of email',
                   Subject = 'the Email Subject',
                   SuppliedEmail = '[email protected]',
                   ...  other defaults set by E2C config 
                   );

// When E2C inserts the Case
insert e2cCase;

// then verify 
..your asserts 

I've omitted some other things E2C does such as setting the Case.ContactId if it found a unique match to an existing Contact.

You can see all the things E2C does by writing a simple before insert trigger and outputting via system.debug the Trigger.new value(s). Then, given a verified E2C email address, send an email with the debug log turned on for the E2C Context user defined in Setup | Support Settings

Notes

  • Be aware that E2C will truncate the incoming email body to the size of Case.Description (default 32000). You can increase this to 131072 by calling Support.
  • The actual EmailMessage object is inserted after the Case is inserted as it needs a parent