Wednesday 14 December 2016

Test Class for Email Service | Test class for InboundEmail


In last month post we created the "Apex Email Service" . Now in this post we will get to know how to write the test class for Apex Email Service.


global class EmailServiceExample 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();
  try 
  {
   List<Contact> contList= [SELECT Id, Name, Email FROM Contact WHERE Email = :email.fromAddress LIMIT 1];
   Task taskObj = new Task();
   taskObj.Description =  email.plainTextBody;
   taskObj.Priority = 'Normal';
   taskObj.Status = 'Inbound Email';
   taskObj.Subject = email.subject;
   taskObj.IsReminderSet = true;
   taskObj.ReminderDateTime = System.now()+1;
   if(contList.size()>0)
   {
    taskObj.WhoId =  contList[0].Id;
   }    
   insert taskObj;    
  }
  catch (Exception e) 
  {
     System.debug('Exception : ' + e);
  }
  result.success = true;
  return result;
 }
}


Test Class

@isTest
private class EmailServiceExampleTest
{
    static testMethod void testUnsubscribe() 
    {
       // Create a new email and envelope object.    
       
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env    = new Messaging.InboundEnvelope();
    
       // Create Test record.
       Contact cont = new Contact(firstName='john', lastName='smith', Email='test@test.com', HasOptedOutOfEmail=false);
       insert cont ;
       
       // Test with the subject that matches the unsubscribe statement.
       email.subject = 'Test Contact Email';
       //email.plainTextBody = 'Test Contact Email';
       env.fromAddress = 'test@test.com';        EmailServiceExample obj= new EmailServiceExample();        obj.handleInboundEmail(email, env );                                  }       }


 Let us know if this will help you

Thanks,
Amit Chaudhary


1 comment:

  1. its email.fromaddress = 'test@test.com'

    ReplyDelete