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

}
}

Testing PageReference in Controllers in Salesforce

Some developers have become frustrated when trying to write unit tests for their Controllers. To be fair, if you don’t know what base you assertions on, it can be hard to test the code. So here are a couple of quick tips for getting it done: Imaging you have a controller's pagereference method like the following:
public class TestingVFController_Controller{
public PageReference save(){
PageReference p=null;
if(this.qp==null || !'yy'.equals(this.qp)){
p=Page.pagenotfound;
p.getParameters().put('error','NoParam');
}
else{
p=Page.homepage;
}}


if qp parameter='yy' then this will redirect to /apex/homepage else /apex/pagenotfound.
for this test class would be

static testMethod void ControllerTest() {
// first test without parameter
PageReference p=Page.HomePage;
Test.setCurrentPage(p);
TestingVFController_Controller ctrl=new TestingVFController_Controller();
String nextPage=ctrl.save().getUrl();

System.assertEquals('/apex/pagenotfound?error=NoParam',nextPage);


//then check with parameter case

ApexPages.currentPage().getParameters().put('qp','yyyy');
ctrl=new TestingVFController_Controller();
nextPage=ctrl.save().getUrl();
System.assertEquals('/apex/homepage', nextPage);