You need to sign in to do that
Don't have an account?
How to write a test class for class that implements Messaging.InboundEmailHandler?
I am new to Email Services and Apex and wanting to learn effective methods for testing classes that implement the Messaging.InboundEmailHandler. Please refer me to any good material for learning test methods and best practices for conducting them. Please see the class code (ProcessApplicant) and Initial Test method Apex Class. I'm only getting 16% code coverage using the current test method.
Thanks,
SCR
/* * This class implements Message.InboundEmailHandler to accept inbound applications for a given position. * It results in a new Candidate (if one doesnt already exist) and Job Description record being created. * Any binary email attachments are automatically transfered to the Job Description as attachments on the Notes and Attachments related list. */ global class ProcessApplicant implements Messaging.InboundEmailHandler { private static final String PHONE_MATCH = 'Phone:'; global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, Messaging.InboundEnvelope envelope) { // Indicates if the message processes successfully, permits an error response to be sent back to the user. Messaging.InboundEmailResult result = new Messaging.InboundEmailResult(); try { // Obtain the applicants name and the position they are applying for from the email. String firstName = email.fromname.substring(0,email.fromName.indexOf(' ')); String lastName = email.fromname.substring(email.fromName.indexOf(' ')); String positionName = email.subject; String emailBody = email.plainTextBody; String emailFrom = envelope.fromAddress; // Process the email information. processApplicantEmail(firstName, lastName, positionName, emailBody, emailFrom, email.binaryAttachments); // Success. result.success = true; } catch (Exception e) { // Return an email message to the user. result.success = false; result.message = 'An error occured processing your message. ' + e.getMessage(); } return result; } public static void processApplicantEmail(String firstName, String lastName, String positionName, String emailBody, String emailFrom, Messaging.InboundEmail.BinaryAttachment[] binaryAttachments) { // Obtain the applicants Phone number from the message body. integer phoneMatchIdx = emailBody.indexOf(PHONE_MATCH); if(phoneMatchIdx==-1) throw new ProcessApplicantException('Please state your phone number following Phone: in your message.'); String phoneNumber = emailBody.substring(phoneMatchIdx+PHONE_MATCH.length()); // Resolve the Id of the Position they are applying for. Id positionId; try { // Lookup the Position they are applying for by name. Position__c position = [select Id from Position__c where name = :positionName limit 1]; positionId = position.Id; } catch (Exception e) { // Record not found. throw new ProcessApplicantException('Sorry the position ' + positionName + ' does not currently exist.'); } // Candidate record for the applicant sending this email. Candidate__c candidate; try { // Attempt to read an existing Candidate by email address. Candidate__c[] candidates = [select Id from Candidate__c where email__c = :emailFrom]; candidate = candidates[0]; } catch (Exception e) { // Record not found, create a new Candidate record for this applicant. candidate = new Candidate__c(); candidate.email__c = emailFrom; candidate.first_name__c = firstName; candidate.last_name__c = lastName; candidate.phone__c = phoneNumber; insert candidate; } // Create the Job Application record. Job_Application__c jobApplication = new Job_Application__c(); jobApplication.Position__c = positionId; jobApplication.Candidate__c = candidate.id; insert jobApplication; // Store any email attachments and associate them with the Job Application record. if (binaryAttachments!=null && binaryAttachments.size() > 0) { for (integer i = 0 ; i < binaryAttachments.size() ; i++) { Attachment attachment = new Attachment(); attachment.ParentId = jobApplication.Id; attachment.Name = binaryAttachments[i].Filename; attachment.Body = binaryAttachments[i].Body; insert attachment; } } // Confirm receipt of the applicants email Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage(); mail.setToAddresses( new String[] { emailFrom }); mail.setSubject('Your job application has been received'); mail.setPlainTextBody('Thank you for submitting your resume. Your application will be reviewed to determine if an interview will be scheduled.'); Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail }); } /* * Represents errors that have occured interpretting the incoming email message */ class ProcessApplicantException extends Exception { } }
//The ProcessApplicant Test: public class ProcessApplicantTest { public static testMethod void ProcessApplicantTest(){ System.debug('Im starting a method'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); email.subject = 'test'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); catcher.handleInboundEmail(email, envelope); } }
Hai Use this
// Success Case
public static testMethod void ProcessApplicantTest(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
Position__c position = [select Id,name from Position__c limit 1];
email.subject = position.name;
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1];
Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
binaryAttachment.Filename = 'test.txt';
String algorithmName = 'HMacSHA1';
Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
Blob.valueOf('test_key'));
binaryAttachment.Body = b;
binaryAttachments[0] = binaryAttachment ;
email.binaryAttachments = binaryAttachments ;
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
System.assertEquals( result.success ,true);
}
// Error Case 1
public static testMethod void ProcessApplicantTestError1(){
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
email.subject = 'testSubject';
email.fromName = 'test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
envelope.fromAddress = 'user@acme.com';
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
// Error Case 2
public static testMethod void ProcessApplicantTestError2(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
email.subject = 'test';
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
//Error Case 3
public static testMethod void ProcessApplicantTestError3(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
Position__c position = [select Id,name from Position__c limit 1];
email.subject = position.name;
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye';
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
Thanks
Thanga
All Answers
Hai Use this
// Success Case
public static testMethod void ProcessApplicantTest(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
Position__c position = [select Id,name from Position__c limit 1];
email.subject = position.name;
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1];
Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment();
binaryAttachment.Filename = 'test.txt';
String algorithmName = 'HMacSHA1';
Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'),
Blob.valueOf('test_key'));
binaryAttachment.Body = b;
binaryAttachments[0] = binaryAttachment ;
email.binaryAttachments = binaryAttachments ;
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope);
System.assertEquals( result.success ,true);
}
// Error Case 1
public static testMethod void ProcessApplicantTestError1(){
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
email.subject = 'testSubject';
email.fromName = 'test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
envelope.fromAddress = 'user@acme.com';
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
// Error Case 2
public static testMethod void ProcessApplicantTestError2(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
email.subject = 'test';
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:123456 Bye';
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
//Error Case 3
public static testMethod void ProcessApplicantTestError3(){
// Create a new email, envelope object and Attachment
Messaging.InboundEmail email = new Messaging.InboundEmail();
Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope();
Position__c position = [select Id,name from Position__c limit 1];
email.subject = position.name;
email.fromName = 'test test';
email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye';
envelope.fromAddress = 'user@acme.com';
// setup controller object
ProcessApplicant catcher = new ProcessApplicant();
catcher.handleInboundEmail(email, envelope);
}
Thanks
Thanga
Check this
http://wiki.developerforce.com/index.php/Code_Sample_-_Testing_Email_Services_with_Inbound_Attachments
Thank both of you very much for your suggestions. I will use these and let you know the results.
SCR
Hello - I created a test class using the code example you provided below and addded an additional method from the wiki. My results:
Summary
I got the ProcessApplicant class to work in Yahoo Mail, but it won't get any results using MS Outlook. Is there some explicit way to specify in the class that MS Outlook is the default mail client?
Expected Behavior:
Use a VisualForce Page (availablePositions) to allow a Candidate to submit a Job Application with an attached résumé using email that will update or create the appropriate records for a Candidate Object, Job Application Object and a Document list for any attachments (i.e. CV, cover latter, etc.) in the force.com Recruiting application. I have error messaging set up to catch and throw any error messages either as Apex Messages in the VisualForce Page or as a plain text exception message sent as an error message to the from address on the inbound email.
Actual Behavior:
Click on the 'Apply' link in the VisualForce Page for the job position you are applying for. MS outlook opens up an email message preloaded with the To Address (Email Services inbound address for ProcessApplicant Email Service) subject that is the job position name and default phone text that is required information.
Workaround:
Create a new message in my Yahoo Mail account with a To Address set as the inbound email address for ProcessApplicant Email Service, a Subject that has a valid Position Name (i.e. POS-000209), and include a phone number preceded by 'Phone:'. Everything works as expected, that is a confirmation email is sent from Salesforce, and records are created in the Force.com Recruiting app for Candidate (email sender) and Job Application (for the position applied for) along with any attachments that are stored in the Notes and Attachments related list.
I'm not sure why it will not work with MS Outlook. Any ideas or help is appreciated.
Thanks,
SCR
Thanks,
SCR
<apex:page controller="AvailablePositionsController" action="{!init}"> <apex:pageBlock > <apex:sectionHeader title="Available Positions" subtitle="The following positions are currently available"/> <apex:pageBlockTable value="{!positions}" var="position"> <apex:column rendered="{!inboundEmailAddr!=null}"> <apex:facet name="header">Action</apex:facet> <apex:outputLink value="mailto:{!inboundEmailAddr}?subject={!position.Name}&body=Phone: (800) 555-1212">Apply</apex:outputLink> </apex:column> <apex:column > <apex:facet name="header">Job Description</apex:facet> <apex:outputText value="{!position.Job_Description__c}"/> </apex:column> <apex:column > <apex:facet name="header">Programming Languages</apex:facet> <apex:outputText value="{!position.Programming_Languages__c}"/> </apex:column> <apex:column > <apex:facet name="header">Salary Grade</apex:facet> <apex:outputText value="{!position.Salary_Grade__c}"/> </apex:column> <apex:column > <apex:facet name="header">Location</apex:facet> <apex:outputText value="{!position.Location_City_State_Country__c}"/> </apex:column> </apex:pageBlockTable> <apex:messages /> </apex:pageBlock> </apex:page>
Hai
Check your Email Service Information ,'Accept Email From' Contains your outlook email Address .
Regards
Thanga
Thanks very much for all of the help. I revised the test methods you provided in your initial response by adding a few error testing comments to better explain the testing procedures in terms of why and how. Code below.
//The ProcessApplicant Test: public class ProcessApplicantTest { // Success Case: Test that email (Header and Body), envelope (Domain and From info) and attachments are received successfully. public static testMethod void ProcessApplicantTest(){ System.debug('Im testing the methods for a Success Case'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; email.subject = position.name; // Sender First Name (FName) and Last Name (LName) are successfully pulled from envelope info. email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:(123)456-7890 Bye'; Messaging.InboundEmail.BinaryAttachment[] binaryAttachments = new Messaging.InboundEmail.BinaryAttachment[1]; Messaging.InboundEmail.BinaryAttachment binaryAttachment = new Messaging.InboundEmail.BinaryAttachment(); binaryAttachment.Filename = 'test.txt'; String algorithmName = 'HMacSHA1'; Blob b = Crypto.generateMac(algorithmName, Blob.valueOf('test'), Blob.valueOf('test_key')); binaryAttachment.Body = b; binaryAttachments[0] = binaryAttachment ; email.binaryAttachments = binaryAttachments ; envelope.fromAddress = 'job-candidate.user@acme.com'; // setup controller object ProcessApplicant catcher = new ProcessApplicant(); Messaging.InboundEmailResult result = catcher.handleInboundEmail(email, envelope); System.assertEquals( result.success ,true); } //Another Success Test with emphasis on MIME type email messages with attachments. public static testMethod void mimeTestMethod() { // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; Messaging.InboundEmail.BinaryAttachment inAtt = new Messaging.InboundEmail.BinaryAttachment(); email.subject = position.name; envelope.fromAddress = 'job-candidate.user@acme.com'; // set the body of the attachment inAtt.body = blob.valueOf('test'); inAtt.fileName = 'my attachment name'; inAtt.mimeTypeSubType = 'plain/txt'; email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] {inAtt }; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } // Error Case 1: Email with required contact information and only 1 part of the fromName. public static testMethod void ProcessApplicantTestError1(){ System.debug('Im testing the methods for a Error Case 1'); Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); //Testing that subject is not a Position Name email.subject = 'testSubject'; email.fromName = 'Name?'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only.Phone:(123)456-7890 Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } // Error Case 2: Email with required contact information and both parts of the fromName without attachments. public static testMethod void noAttachmentTest(){ System.debug('Im testing the methods for a Error Case 2'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); //Subject is not position.name email.subject = 'test'; email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Phone:(123)456-7890 Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } //Error Case 3: Email with position.name in the subject, but missing required call back (phone) information. public static testMethod void ProcessApplicantTestError3(){ System.debug('Im testing the methods for a Error Case 3'); // Create a new email, envelope object and Attachment Messaging.InboundEmail email = new Messaging.InboundEmail(); Messaging.InboundEnvelope envelope = new Messaging.InboundEnvelope(); Position__c position = [select Id,name from Position__c limit 1]; email.subject = position.name; email.fromName = 'FName LName'; email.plainTextBody = 'Hello, this a test email body. for testing purposes only. Bye'; envelope.fromAddress = 'job-candidate.user@acme.com'; // instantiate the class and test it with the data in the testMethod ProcessApplicant emailServiceObject = new ProcessApplicant(); emailServiceObject.handleInboundEmail(email, envelope); } }
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); }