Ajax (1) Apex Class (12) Apex Trigger (2) Community (2) Home Page (1) HTML (4) Integration (3) JS (7) KB (1) Label (1) Licenses (1) Listing (1) Log (1) OOPs (5) Sharing (1) Static Resource (1) Test Class (3) URI (1) Visualforce (10)

Sunday 2 March 2014

How to Unit Test Recieving Email in Apex

Suppose you have a class like this for recieving email



/**
* Email services are automated processes that use Apex classes
* to process the contents, headers, and attachments of inbound
* email.
create account from email subject
create contacts from email cc
create text and binary attachments if any

*/
global class EmailDemoReceive implements Messaging.Inboundemailhandler {

global Messaging.Inboundemailresult handleInboundemail(Messaging.Inboundemail email, Messaging.Inboundenvelope env ){
Account account;
Messaging.Inboundemailresult result = new Messaging.Inboundemailresult();
try{

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;
}
}


for(Messaging.Inboundemail.Binaryattachment Battachment : email.binaryAttachments){
Attachment a = new attachment();
a.Name= battachment.fileName;
a.body= battachment.body;
a.parentID= account.id;
try{
insert a;}
catch(DMLException e){
system.debug(e.getMessage());
}
}

for(Messaging.Inboundemail.Textattachment tAttachment : email.textAttachments) {
Attachment a = new Attachment();
a.name= tAttachment.fileName;
a.body= blob.valueOf(tAttachment.body);
a.parentID= account.id;
insert a;
}

result.success= true;
}
catch(Exception e){
result.success=false;
result.Message='oops, failed again';

}

return result;
}

}



Unit class for testing this would be


@IsTest
private class EmailDemoReceiveHandlerTests {

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

// Set up your data if you need to

// Create the email body
email.plainTextBody = 'This should become a note';
email.fromAddress ='test@test.com';
String contactEmail = 'jsmith@salesforce.com';
email.ccAddresses = new String[] {'Jon Smith <' + contactEmail + '>'};
email.subject = 'Dummy Account Name 123';

EmailDemoReceive edr = new EmailDemoReceive();

Test.startTest();
Messaging.InboundEmailResult result = edr.handleInboundEmail(email, env);
Test.stopTest();

System.assert (result.success, 'InboundEmailResult returned a failure message');

Account [] accDb = [select ID from Account where name=:email.subject];
System.assertEquals (1, accDb.size(),'Account was not inserted');
Contact [] cDb = [select firstname,lastname from Contact where email=:contactEmail];
System.assertEquals (1, cDb.size(),'Contact was not inserted!');
Contact c = CDb[0];
System.assertEquals ('Jon', c.firstName);
System.assertEquals ('Smith', c.LastName);
Note [] nDb = [select body from Note where ParentID=:accDb[0].id];
System.assertEquals (1,nDb.size(), 'A note should have been attached');
System.assertEquals (email.plainTextBody, nDb[0].body);

}
}

No comments:

Post a Comment