function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Anu Singh 40Anu Singh 40 

Test class for InboundMessaging

Hi All
I have to write a test class for following class. I wrote  test class for my apex class but it only giving 35% coverage.
 can anyone help me
Thanks in Advance
global class Handle_Incoming_Email_Forwarding implements Messaging.InboundEmailHandler {
    
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                           Messaging.InboundEnvelope env)
    {
String myPlainText= '';
        String toAdd=(String.valueOf(email.toAddresses).contains('(') && String.valueOf(email.toAddresses).contains(')')) ? String.valueOf(email.toAddresses).replace('(','').replace(')','') : String.valueOf(email.toAddresses);
                String ccAdd=email.ccAddresses == NULL ? '' : (String.valueOf(email.ccAddresses).contains('(') && String.valueOf(email.ccAddresses).contains(')'))? String.valueOf(email.ccAddresses).replace ('(','').replace(')','') : String.valueOf(email.ccAddresses);
                myPlainText = 'To: '+toAdd+'\n'+ 'CC: '+ccAdd+ '\n'+ 'From Addresses: '+String.valueOf(email.fromAddress).replace('(','').replace(')','')+ '\n'+ 'Subject: '+email.subject+ '\n'+email.plainTextBody;
 
        Task[] newTask = new Task[0];
        Task[] newTask1 = new task[0];
        Task[] newTask2 = new task[0];
        
        try {       
 Id UserId= [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses LIMIT 1].Id;
                for(Lead obj: [SELECT Id, Name, Email  FROM Lead WHERE Email = :email.fromAddress]){
                    task t=new Task(
                                     ActivityDate = System.today(),
                        Description =  myPlainText,                          
                                          Priority = 'Normal',
                                          Status = 'Completed',
                                          Subject = 'Email: '+email.subject,
                                          IsReminderSet = true,
                                          TaskSubtype='Email',
                                          RecurrenceStartDateOnly = System.today(),
                        
                                          WhoId =  obj.ID);
                                         
                    insert t;
                    EmailMessage e = new EmailMessage();
                    e.ActivityId=t.id;
                    
                    
                    
                    
                    newTask2.add(new Task(                         
                                      Priority = 'Normal',
                                      Status = 'Inbound Email',
                                      Subject = 'Reply',
                                      IsReminderSet = true,
                                      Description =  myPlainText,
                                     ActivityDate = System.today()+7,
                                      OwnerId= UserId,
                                      //ActivityDate = System.today().addDays(7),
                                      RecurrenceStartDateOnly = System.today(),
                                      WhoId =  obj.ID                   
                                     )); 
                }
 Id UserId= [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses LIMIT 1].Id;
                for(Lead obj: [SELECT Id, Name, Email  FROM Lead WHERE Email = :email.fromAddress]){
                    task t=new Task(
                                     ActivityDate = System.today(),
                        Description =  myPlainText,                          
                                          Priority = 'Normal',
                                          Status = 'Completed',
                                          Subject = 'Email: '+email.subject,
                                          IsReminderSet = true,
                                          TaskSubtype='Email',
                                          RecurrenceStartDateOnly = System.today(),
                        
                                          WhoId =  obj.ID);
                                         
                    insert t;
                    EmailMessage e = new EmailMessage();
                    e.ActivityId=t.id;
                    
                    
                    
                    
                    newTask2.add(new Task(                         
                                      Priority = 'Normal',
                                      Status = 'Inbound Email',
                                      Subject = 'Reply',
                                      IsReminderSet = true,
                                      Description =  myPlainText,
                                     ActivityDate = System.today()+7,
                                      OwnerId= UserId,
                                      //ActivityDate = System.today().addDays(7),
                                      RecurrenceStartDateOnly = System.today(),
                                      WhoId =  obj.ID                   
                                     )); 
                }


test class:
@istest
public class TEST_Handle_Incoming_Email_Forwading {   
   static testMethod void TestinBoundEmail()
   {
         String contactEmail = 'contactEmail@test.com';
      
       Messaging.InboundEmail email = new Messaging.InboundEmail() ;
       Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
 email.subject = 'Create Contact';
      email.fromAddress = contactEmail;
      email.ccAddresses = (new String[] { 'person2@salesforce.com', 'person2@salesforce.com' });
      email.fromName='test';
      email.htmlBody='this is Html Body for email';
      email.plainTextBody = 'email body';
      email.toAddresses=(new String[] { 'test@salesforce.com', 'test2@salesforce.com' });
      email.replyTo='reply@email.com';
      Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
      attachment.body = blob.valueOf('my attachment text');
      attachment.fileName = 'textfileone.txt';
      attachment.mimeTypeSubType = 'text/plain';
       
      email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
          
    Handle_Incoming_Email_Forwarding testEmail = new Handle_Incoming_Email_Forwarding();
     testEmail.handleInboundEmail(email, env);
   }
}

for loop is not coverd by this test class. What else I can write to cover this class
Maharajan CMaharajan C
Hi Anu Singh,

You have to insert the lead record in test class to cover the for loop:
 
@istest
public class TEST_Handle_Incoming_Email_Forwading {   
    static testMethod void TestinBoundEmail()
    {
        String contactEmail = 'AnuSingh123@gmail.com';
        Id AdminProfileID = [Select Id From profile Where Name = 'System Administrator' Limit 1].Id;  
        User u = new User( email=contactEmail, profileid = AdminProfileID , UserName='AnuSingh789@gmail.com',
                          alias='anuSin',
                          TimeZoneSidKey='America/New_York',
                          LocaleSidKey='en_US',
                          EmailEncodingKey='ISO-8859-1',
                          LanguageLocaleKey='en_US',
                          FirstName = 'Anu',
                          LastName = 'Singh',
                          IsActive = true
                         );
        
        insert u;
        
        Lead l = new Lead(lastName = 'AnuSingh', Company = 'Salesforce', Email = contactEmail, status = 'Open');
        insert l;
        
        Messaging.InboundEmail email = new Messaging.InboundEmail() ;
        Messaging.InboundEnvelope env = new Messaging.InboundEnvelope();
        email.subject = 'Create Contact';
        email.fromAddress = contactEmail;
        email.ccAddresses = (new String[] { 'person2@salesforce.com', 'person2@salesforce.com' });
        email.fromName='test';
        email.htmlBody='this is Html Body for email';
        email.plainTextBody = 'email body';
        email.toAddresses=(new String[] { 'AnuSingh123@gmail.com','test@salesforce.com', 'test2@salesforce.com' });
        email.replyTo='reply@email.com';
        Messaging.InboundEmail.BinaryAttachment attachment = new Messaging.InboundEmail.BinaryAttachment();
        attachment.body = blob.valueOf('my attachment text');
        attachment.fileName = 'textfileone.txt';
        attachment.mimeTypeSubType = 'text/plain';
        
        email.binaryAttachments = new Messaging.inboundEmail.BinaryAttachment[] { attachment };
            
            Handle_Incoming_Email_Forwarding testEmail = new Handle_Incoming_Email_Forwarding();
        testEmail.handleInboundEmail(email, env);
    }
}

Thanks,
Maharajan.C
Anu Singh 40Anu Singh 40
Hi Maharajan.C
Thank you for reply. I have already tried test class with lead but  I am geeting same 35% coverage. After your reply I tried with user and profile but this time also 35 %
Is there any other mistake I  am making or I am have consider to craete a lead data. Lead has some cutom fields which are mandatory. is it may be a case to fail lead insertion.


Thanks,
Anu Singh
Abdul KhatriAbdul Khatri
Hi Anu,

Not sure what exactly you want to get from your code. I see too many issues as it is not following the apex best practices.

As per my understanding, It looks like you want to create Two Task Per email for the lead.

You also didn't provide full code and also didn't undertand the purpose of doing the following in the code.
EmailMessage e = new EmailMessage();
e.ActivityId=t.id;
First we need to fix your code before we look into the converage. I made a little effort per my understanding and commented all your code instead of removing it. Let me know if this work as you expected.
 
global class Handle_Incoming_Email_Forwarding implements Messaging.InboundEmailHandler{
    
    global Messaging.InboundEmailResult handleInboundEmail(Messaging.inboundEmail email, 
                                                           Messaging.InboundEnvelope env)
    {
        
        Messaging.InboundEmailResult result = new Messaging.InboundEmailResult();
        
        String myPlainText= '';
        String toAdd=(String.valueOf(email.toAddresses).contains('(') && String.valueOf(email.toAddresses).contains(')')) ? String.valueOf(email.toAddresses).replace('(','').replace(')','') : String.valueOf(email.toAddresses);
                String ccAdd=email.ccAddresses == NULL ? '' : (String.valueOf(email.ccAddresses).contains('(') && String.valueOf(email.ccAddresses).contains(')'))? String.valueOf(email.ccAddresses).replace ('(','').replace(')','') : String.valueOf(email.ccAddresses);
                myPlainText = 'To: '+toAdd+'\n'+ 'CC: '+ccAdd+ '\n'+ 'From Addresses: '+String.valueOf(email.fromAddress).replace('(','').replace(')','')+ '\n'+ 'Subject: '+email.subject+ '\n'+email.plainTextBody;
 
        //Task[] newTask = new Task[0];
        //Task[] newTask1 = new task[0];
        //Task[] newTask2 = new task[0];

		Map<String, List<Task>> emailTaskMap = new Map<String, List<Task>>();
        Map<String, Lead> emailLeadMap = new Map<String, Lead>();
        Map<String, User> emailUserMap = new Map<String, User>();
        List<Task> taskListToInsert = new List<Task>();
        try { 
            
            for(Lead lead : [SELECT Id, Name, Email  FROM Lead WHERE Email = :email.fromAddress]){               
                emailLeadMap.put(lead.Email, lead);
            }
            
            for(User user : [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses]){
                emailUserMap.put(user.Email, user);
            }
            
            for(Lead obj : emailLeadMap.Values()){
                
                
				Task t1 = new Task(
                    ActivityDate = System.today(),
                    Description =  myPlainText,                          
                    Priority = 'Normal',
                    Status = 'Completed',
                    Subject = 'Email: '+ email.subject,
                    IsReminderSet = true,
                    TaskSubtype='Email',
                    RecurrenceStartDateOnly = System.today(),
                    WhoId =  emailLeadMap.get(obj.Email).Id
                );
 
				Task t2 = new Task(
                    Priority = 'Normal',
                    Status = 'Inbound Email',
                    Subject = 'Reply',
                    IsReminderSet = true,
                    Description =  myPlainText,
                    ActivityDate = System.today()+7,
                    OwnerId= emailUserMap.get(obj.Email).Id,
                    //ActivityDate = System.today().addDays(7),
                    RecurrenceStartDateOnly = System.today(),
                    WhoId =  emailLeadMap.get(obj.Email).Id
                );
                
                emailTaskMap.put(obj.Email, new List<Task>{t1, t2});
                taskListToInsert.addAll(new List<Task> {t1, t2});
                //EmailMessage e = new EmailMessage();
                //e.ActivityId=t.id;                               
                
            }
            
            if(!taskListToInsert.IsEmpty()){ 
                Database.insert(taskListToInsert);
            }            
              /*  Id UserId= [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses LIMIT 1].Id;
                for(Lead obj: [SELECT Id, Name, Email  FROM Lead WHERE Email = :email.fromAddress])
                {
                    task t=new Task(
                                    ActivityDate = System.today(),
                                    Description =  myPlainText,                          
                                    Priority = 'Normal',
                                    Status = 'Completed',
                                    Subject = 'Email: '+email.subject,
                                    IsReminderSet = true,
                                    TaskSubtype='Email',
                                    RecurrenceStartDateOnly = System.today(),
                                    WhoId =  obj.ID);
                                         
                    insert t;

                    EmailMessage e = new EmailMessage();
                    e.ActivityId=t.id;                 
                    
                    newTask2.add(new Task(                         
                                    Priority = 'Normal',
                                    Status = 'Inbound Email',
                                    Subject = 'Reply',
                                    IsReminderSet = true,
                                    Description =  myPlainText,
                                    ActivityDate = System.today()+7,
                                    OwnerId= UserId,
                                    //ActivityDate = System.today().addDays(7),
                                    RecurrenceStartDateOnly = System.today(),
                                    WhoId =  obj.ID                   
                                 )); 
                }

                //Id UserId= [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses LIMIT 1].Id;
                UserId= [SELECT Id, Name, Email FROM User WHERE Email =:email.toAddresses LIMIT 1].Id;
                for(Lead obj: [SELECT Id, Name, Email  FROM Lead WHERE Email = :email.fromAddress])
                {
                    task t=new Task(
                                    ActivityDate = System.today(),
                                    Description =  myPlainText,                          
                                    Priority = 'Normal',
                                    Status = 'Completed',
                                    Subject = 'Email: '+email.subject,
                                    IsReminderSet = true,
                                    TaskSubtype='Email',
                                    RecurrenceStartDateOnly = System.today(),
                                    WhoId =  obj.ID);
                                         
                    insert t;
                    EmailMessage e = new EmailMessage();
                    e.ActivityId=t.id;
                      
                    newTask2.add(new Task(                         
                                      Priority = 'Normal',
                                      Status = 'Inbound Email',
                                      Subject = 'Reply',
                                      IsReminderSet = true,
                                      Description =  myPlainText,
                                     ActivityDate = System.today()+7,
                                      OwnerId= UserId,
                                      //ActivityDate = System.today().addDays(7),
                                      RecurrenceStartDateOnly = System.today(),
                                      WhoId =  obj.ID                   
                                     )); 
                }*/
            }catch(Exception ex){
        		result.success = false;
                return result;
            }
        result.success = true;
    	return result;
    }

}