function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RajSharanRajSharan 

How to write a test class for class that implements Messaging.InboundEmailHandler? - Email to Lead

Ref: http://community.salesforce.com/sforce/board/message?board.id=Visualforce&view=by_date_ascending&message.id=15324

 

I'm facing the same problem. I've created an "Email to Lead" class. Due to Campaign constraints, I've had to hardcode that information.

 

My test class is not going past  33%.

 

/**
******************************************************************************
Name : EmailToLeadOrContactTask
Objective : Create Lead or Contact Activity
Input Parameter :
Output Parameter:
Calls :
Called from :
Contact : rsharan@navinet.net
Modification History :-
Created/Modified by Created/Modified Date Purpose
-----------------------------------------------------------------------------
1. Raj Sharan 2/24/2010 - Create class
-----------------------------------------------------------------------------
******************************************************************************
*/

/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
*/
global class EmailToLeadOrContactTask implements Messaging.InboundEmailHandler {

global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope env) {

// Create an inboundEmailResult object for returning the result of the Apex Email Service
Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();

// Default is Info

String strOwnerID = 'OwnerInfo'; //MASKED
String strCampaignID = 'CampaignInfo'; //MASKED

// Set CampaignID, UserID, etc. based on the To address

if(env.toAddress.compareTo('abc@123.in.salesforce.com') == 0) {
//System.debug('Compare: ' + env.toAddress.compareTo('abc@123.in.salesforce.com')); //MASKED
strOwnerID = 'Owner2'; //MASKED
strCampaignID = 'Campaign2'; //MASKED
}

// Try to lookup any contacts based on the email from address
Contact[] ContactList = [Select Id, Name, Email
From Contact
Where Email = :email.fromAddress
Limit 1];
if (ContactList.Size() > 0) {
for (Contact contact : ContactList){

// Add Contact to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
ContactId = contact.Id);
// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created
Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = contact.Id,
OwnerId = strOwnerID);

// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// If no matching contact found, find if the lead already exists
Lead[] LeadList = [Select Id, Email, ConvertedContactId
From Lead
Where Email = :email.fromAddress
Limit 1];
if (LeadList.Size() > 0) {
for (Lead lead : LeadList){
// Add Lead to Campaign after checking if the Lead was already converted to a Contact
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID);
if(lead.ConvertedContactId != null) {
newCampaignMember.ContactId = lead.ConvertedContactId;
}
else {
newCampaignMember.LeadId = lead.Id;
}

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// New Task object to be created - on Lead or on converted Contact
String recordID = null;
if(lead.ConvertedContactId != null) {
recordID = lead.ConvertedContactId;
}
else {
recordID = lead.Id;
}

Task newTask = new Task(Description = email.plainTextBody,
Priority = 'Normal',
Status = 'Inbound Email',
Subject = email.subject,
IsReminderSet = true,
ReminderDateTime = System.now() + 1,
WhoId = recordID,
OwnerId = strOwnerID);


// Insert the new Task
try {
insert newTask;
//System.debug('New Task Object: ' + newTask.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}
else {
// Retrieves the sender's first and last names
String fName = email.fromname.substring(0,email.fromname.indexOf(' '));
//System.debug('First Name: ' + fName);
String lName = email.fromname.substring(email.fromname.indexOf(' '));
//System.debug('Last Name: ' + lName);

// Parse company name
String strCompany = email.fromAddress.substring(email.fromAddress.indexOf('@') + 1, email.fromAddress.indexOf('.', email.fromAddress.indexOf('@')));
//System.debug('Company Name: ' + strCompany);

Lead newLead = new Lead(Description = 'Subject: ' + email.subject + '\n\nBody:\n' + email.plainTextBody,
FirstName = fName,
LastName = lName,
Company = strCompany,
Email = email.fromAddress,
LeadSource = 'Inbound Email',
OwnerId = strOwnerID);

// Insert the new lead
try {
insert newLead;
//System.debug('New Lead Object: ' + newLead.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}

// Add Lead to Campaign
CampaignMember newCampaignMember = new CampaignMember(CampaignId = strCampaignID,
LeadId = newLead.Id);

// Insert the record
try {
insert newCampaignMember;
//System.debug('New Campaign Member: ' + newCampaignMember.Id);
}
catch (Exception e) {
system.debug('Error: ' + e);
}
}
}

// Set the result to true. No need to send an email back to the user
// with an error message

result.success = true;

// Return the result for the Apex Email Service
return result;
}
}

 

 

Test Class

 

static testMethod void emailToContactTaskTestMethod() {
Account aData = new Account(Name = 'Test1',
OfficeNID__c = '1316585');
insert aData;
System.assert(aData.Name == 'Test1');

Contact newContact = new Contact(LastName = 'TestContact',
AccountID = aData.Id,
Office_NID__c = aData.OfficeNID__c,
email = 'TestContact' + '@gmail.com');
insert newContact;
System.assert(newContact.Office_NID__c == '1316585');

// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForContact';
email.plainTextBody = 'Test';
env.fromAddress = 'TestContact@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

static testMethod void emailToLeadTestMethod() {

Lead newLead = new Lead(LastName = 'TestLead',
Company = 'TestCompany',
email = 'TestLead' + '@gmail.com');
insert newLead;
System.assert(newLead.Company == 'TestCompany');

Campaign aCampaign = new Campaign(Name = 'A Campaign');
insert aCampaign;
System.assert(aCampaign.Name == 'A Campaign');

// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForLead';
email.plainTextBody = 'Test';
env.fromAddress = 'TestLead@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

static testMethod void emailToNewLeadTestMethod() {
// Create a new email, envelope object
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();

email.subject = 'TestForNewLead';
email.plainTextBody = 'Test';
env.fromAddress = 'NewTestLead@gmail.com';
env.toAddress = 'abc@123.in.salesforce.com';

EmailToLeadOrContactTask emailServiceObj = new EmailToLeadOrContactTask();
Messaging.InboundEmailResult result = emailServiceObj.handleInboundEmail(email, env);
System.assertEquals(result.success, true);
}

 

ReidCReidC

Hi Raj,

 

There are a few things I would do to boost coverage.  Note that I have not read through your code in  detail -- this is more of a general approach that works for me.

 

* break your code into smaller chunks and test those smaller chunks.  Right now you have one big method with a lot of branches.  my rule of thumb is that a method should be 20 functional lines or smaller.

 

* refactor your code so that a utility class does the heavy lifting and the inbound message handler calls the utility.  That utility class becomes a lot easier to test.

 

* in your code, you have a number of try / catch.  you definitely want to use try catch, but the way you are using it right now, you don't have a good way to verify that an exception is being thrown when it should be and so it's hard to test.

 

When combined, these three things have helped me quite a bit when it comes to testing.

 

Hope that helps.  Once you've done that, if you want to share some code back here I'd be happy to take a look at it again.


Regards

 

 

RajSharan1RajSharan1
Thanks for the information! I will try to break it up and post updated code soon.