+ Start a Discussion

Email Services Test Class



I need some help creating a test class for the code below.  We are using Email to Case and we wanted to be able associate the Contact to the Case record.  I was able to find this code that allows us to do that using Email Services.  Please share any test class for this code. 



global class cases implements Messaging.InboundEmailHandler {

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

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

String myPlainText = '';

// Initialize the Contact ID, so if no Contact is found, a case is still created
ID vconID;

// Add the email plain text into the local variable

myPlainText = email.plainTextBody.substring(0, email.plainTextBody.indexOf('<stop>'));
catch (System.StringException e)
myPlainText = email.plainTextBody;
System.debug('No <stop> in email: ' + e);

// new Case object to be created

Case[] newCase = new Case[0];

// Try to lookup any contacts based on the email from address
// If there is more than 1 contact with the same email address
// an exception will be thrown and the catch statement will be called
try {
Contact vCon = [Select Id, Name, Email
From Contact
Where Email = :email.fromAddress
Limit 1];

// Add a new Case to the contact record we just found above - if not Contact found, value remains null
vconID = vCon.ID;

// Insert the new Case and it will be created and appended to the contact record

System.debug('New Case Object: ' + newCase );
// If there is an exception with the query looking up
// the contact this QueryException will be called.
// and the exception will be written to the Apex Debug logs

catch (System.QueryException e) {
System.debug('Query Issue: ' + e);

newCase.add(new Case(Description = myPlainText,
Priority = 'Medium',
Status = 'New',
Subject = email.subject,
ContactId = vconID));
insert newCase;

// 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 Force.com Email Service
return result;

static testMethod void testCases() {

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

// Create the plainTextBody and fromAddres for the test
email.plainTextBody = 'Here is my plainText body of the email';
email.fromAddress ='shillyer@salesforce.com';

Cases caseObj = new Cases();
caseObj.handleInboundEmail(email, env);


shraddha kawaneshraddha kawane
In the test method,
1. create a new email and envelope object
2. setup the data for the email i.e. subject, fromname & fromAddress.
3. add an attachment
4.call the email service class and test it with the data in the testMethod
5.find the attachment
6.send the mail.