I am looking to complete the Code Coverage requirement for deploying Apex Classes. I have taken the inbound email class that Salesfoce has made available for use with custom objects, but now I need to test the code to deploy to production. I am struggling to understand the Apex Testing code and have a deadline I am trying to meet.

Any help with constructing the test code for the following Apex Class would be very much appreciated.

global class EmailToSalesForce implements Messaging.InboundEmailHandler {
  global Messaging.InboundEmailResult handleInboundEmail(Messaging.InboundEmail email, 
                                                         Messaging.Inboundenvelope envelope) {

Account account;
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

try {

// Look for account whose name is the subject and create it if necessary
if ([select count() from Account where Name =:email.subject] == 0) {
  account = new Account();
  account.Name = email.subject;
  insert account;
} else {
  account = [select Id from Account where Name =:email.subject];

// Convert cc'd addresses to contacts
for (String address: email.ccAddresses) {
  Contact contact = new Contact();
  Matcher matcher = Pattern.compile('<.+>').matcher(address);

  // Parse addresses to names and emails
  if (matcher.find()) {
    String[] nameParts = address.split('[ ]*<.+>')[0].replace('"', '').split('[ ]+');

    contact.FirstName = nameParts.size() > 1? nameParts[0]: '';
    contact.LastName = nameParts.size() > 1? nameParts[nameParts.size()-1]: nameParts[0];
    contact.Email = matcher.group().replaceAll('[<>]', '');
  } else {
    contact.LastName = address;
    contact.Email = address;

  // Add if new
  if ([select count() from Contact where Email =:contact.Email] == 0) {
    contact.AccountId = account.Id;
    insert contact;

// Turn email body into note
Note note = new Note();

note.Title = email.fromName + ' (' + DateTime.now() + ')';
note.Body = email.plainTextBody;
note.ParentId = account.Id;
insert note;

// Save attachments, if any
for (Messaging.Inboundemail.TextAttachment  tAttachment :email.textAttachments) {
  Attachment attachment = new Attachment();

  attachment.Name = tAttachment.fileName;
  attachment.Body = Blob.valueOf(tAttachment.body);
  attachment.ParentId = account.Id;
  insert attachment;
for (Messaging.Inboundemail.BinaryAttachment  bAttachment :email.binaryAttachments) {
  Attachment attachment = new Attachment();

  attachment.Name = bAttachment.fileName;
  attachment.Body = bAttachment.body;
  attachment.ParentId = account.Id;
  insert attachment;

      result.success = true;
      result.message = (email.subject + ' matched');
    } catch (Exception e) {
      result.success = false;
      result.message = 'Sorry, an error has occured. Please contact your Salesforce Administrator.';

    return result;

PS - i do not know why there is no "code" option for posting in this forum? Maybe i am just using the preformatted text option wrong..?

  • There is its the {} option on the ask a question screen - I've added it for you. With regards to your question what test code do you have so far, what specifically are you struggling with?
    – Girbot
    Jun 19, 2015 at 13:32
  • all of it :). So, I've been reading the documentation that Salesforce has - I understand what it is that I need to do, but I am having a difficult time getting started. Jun 19, 2015 at 13:36
  • Also - to be clear, I am okay with being pointed in the right direction to read about Testing apex code. It's just so far, from what Salesforce has offered, I am still struggling. If there are better resources available that you are familiar with, please introduce me. I don't want to just ask someone to write the test code for me if it's not needed. Jun 19, 2015 at 13:43

1 Answer 1


Here is an article from Salesforce about a simple testMethod for an inbound email handler for an email which has an attachment on it.


Your test code might look a little bit like the example below, adapted from the link above. Don't skimp on the assertions at the end of the test method. You need to be sure that your code is doing what you expect and assertions are the only way to really be certain.

private class InboundEmailHandlerTest {

    static testMethod void myTestMethod() {

          /* Set up all of the prerequisite data that your email handler needs */
          /* Accounts, Contacts, required field values, etc. */

          // Create a new email, envelope object and an Attachment
          Messaging.InboundEmail email = new Messaging.InboundEmail();
          Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
          Messaging.InboundEmail.BinaryAttachment inboundAttachment = new Messaging.InboundEmail.BinaryAttachment();

          email.subject = 'Acme Inc.';
          env.fromAddress = '[email protected]';

          // set the body of the attachment
          inboundAttachment.body = blob.valueOf('test');
          inboundAttachment.fileName = 'Email_Attachment.txt';
          inboundAttachment.mimeTypeSubType = 'text/plain';

          email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { inboundAttachment }; 


          // create an instance of the EmailToSalesForce class and test it with the data in the testMethod
          EmailToSalesForce emailServiceObj = new EmailToSalesForce();
          emailServiceObj.handleInboundEmail(email, env );                      


          // Make assertions about proper behavior        
          // query for data in your org to ensure that the email handler class did the correct thing
          // i.e. created an account that didn't exist, saved any attachments that existed on the email, etc.

          // List<Account> accounts = [SELECT Id, Name, (SELECT Id, Name FROM Attachments) FROM Account WHERE Name = 'Acme Inc.'];
          // system.assertEquals(1, accounts.size(), 'There should be exactly one account named Acme Inc.');

          // Account theAccount = accounts[0];
          // system.assertEquals(1, theAccount.Attachments.size(), 'There should be exactly one attachment on the account.');

          // Attachment theAttachment = theAccount.Attachments[0];
          // system.assertEquals('Email_Attachment.txt', theAttachment.Name, 'The attachment name is not correct.');


  • Update: Your test code works great, but I'm only getting to 64% code coverage - need to hit that magical 75% :) Jun 19, 2015 at 16:49
  • Glad it's functional! I'm not going to write the test code for the various paths that your email handler class can take through its logic, I'll leave the exercise of creating additional methods for the alternate behavior testing up to you. :-)
    – Mark Pond
    Jun 19, 2015 at 16:57

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .