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
SFDC GuestSFDC Guest 

Test class for Batch apex - email messaging class

Hi, Please let me know how to cover EmailMessaging class in below code:

Class:
global class UpdateLastWorkedDate_onContactBatch implements Database.Batchable<sObject>, Schedulable {
     public EmailTemplate et{get;set;}
      
    global DataBase.QueryLocator start(Database.BatchableContext bc){
                       system.debug('>>>>');

        return DataBase.getQueryLocator([select id,owner.email,TR1__Candidate_Status__c,Last_Day_Worked__c,TRSCHED__Compliance_Owner__r.email from contact where Last_Day_Worked__c!=null]);
        }
    global void execute(Database.BatchableContext BC, List<contact> scope)
       {
                      system.debug('>>>>');

       list<contact> conlist=new list<contact>();
       et=[select id,Name FROM EmailTemplate where Name='3monthsgap' Limit 1];
       list<string> to=new list<string>();
       List<Messaging.SingleEmailMessage> mailsList = new List<Messaging.SingleEmailMessage>();

       for(contact c:scope){
               system.debug('>>>>');

        integer i;
        //i=system.today().monthsBetween(c.Last_Day_Worked__c);
        i=c.Last_Day_Worked__c.monthsBetween(system.today());

        system.debug('>>>>'+i);
        if(i==3){
        c.TR1__Candidate_Status__c='InActive';
        conlist.add(c);
        }
        if(i==2)
        {
                       system.debug('>>>>');

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               to.add(c.owner.email);
                 to.add(c.TRSCHED__Compliance_Owner__r.email);

                 mail.setTargetObjectId(c.id);
                 mail.setSaveAsActivity(false);
                 mail.setTreatTargetObjectAsRecipient(false);
                 mail.setTemplateId(et.id);
                 //mail.setWhatId(AQ.id);
                 mail.setToAddresses(to);
          mailsList.add(mail);
        
        }
       }
      if(conlist.Size()>0){

       update conlist;
       }
        if(mailsList.Size()>0){
                       system.debug('>>>>');

            Messaging.sendEmail(mailsList);
            }  
       
       }   
    
    global void finish(Database.BatchableContext BC){
        }
       global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
    }
    
}

Test class: 59% coverage

@isTest
public class Test_UpdateLastWorkedDate_onContactBatch {
public static testMethod void test() 
     {
   /*   Profile p = [SELECT Id FROM Profile WHERE Name='system administrator'];
         
    User us = new User(Alias='Admin',Email='test@gamil.com',LastName='Testing',Username='standardus@testorg.com',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id, 
           TimeZoneSidKey='America/Los_Angeles',EmailEncodingKey='UTF-8');
    insert us;*/
   User us = [Select id from User where Id = :UserInfo.getUserId()];
         
    Account acc = new Account(Name = 'test13');
    insert acc;
    
    Contact con = new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-90), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id);
    insert con;
         
 //     EmailTemplate eT = new EmailTemplate (developerName = 'X3monthsgap', subject='test', FolderId = UserInfo.getUserId(), TemplateType= 'Text', Name = '3monthsgap'); 
     //    insert eT;
   System.runAs(us)
   {
   Test.startTest();
     UpdateLastWorkedDate_onContactBatch obj = new UpdateLastWorkedDate_onContactBatch();
     DataBase.executeBatch(obj); 
         
   Test.stopTest();
   }  
    }
    
}

Below code not covered:

 Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               to.add(c.owner.email);
                 to.add(c.TRSCHED__Compliance_Owner__r.email);

                 mail.setTargetObjectId(c.id);
                 mail.setSaveAsActivity(false);
                 mail.setTreatTargetObjectAsRecipient(false);
                 mail.setTemplateId(et.id);
                 //mail.setWhatId(AQ.id);
                 mail.setToAddresses(to);
          mailsList.add(mail);
       
 global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
    
Thanks
Best Answer chosen by SFDC Guest
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi,

Modify Your Test Class with this one, 
 
public class Test_UpdateLastWorkedDate_onContactBatch {
public static testMethod void test() 
     {
   /*   Profile p = [SELECT Id FROM Profile WHERE Name='system administrator'];
         
    User us = new User(Alias='Admin',Email='test@gamil.com',LastName='Testing',Username='standardus@testorg.com',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id, 
           TimeZoneSidKey='America/Los_Angeles',EmailEncodingKey='UTF-8');
    insert us;*/
   User us = [Select id from User where Id = :UserInfo.getUserId()];
         
    Account acc = new Account(Name = 'test13');
    insert acc;
    // Modifed By Prosenjit 
    List<Contact> conList = new List<Contact>();
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-90), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-60), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
    insert conList;
         
 //     EmailTemplate eT = new EmailTemplate (developerName = 'X3monthsgap', subject='test', FolderId = UserInfo.getUserId(), TemplateType= 'Text', Name = '3monthsgap'); 
     //    insert eT;
   System.runAs(us)
   {
   Test.startTest();
     UpdateLastWorkedDate_onContactBatch obj = new UpdateLastWorkedDate_onContactBatch();
     DataBase.executeBatch(obj); 
     
		// code to test schedules
		UpdateLastWorkedDate_onContactBatch schClass = new UpdateLastWorkedDate_onContactBatch();
		String sch = '0 0 23 * * ?'; 
		system.schedule('Test Territory Check', sch, schClass);
		
   Test.stopTest();
   }  
    }
    
}

If this solution works please make this as a best answer for future searches.

Thanks,
Prosenjit​

All Answers

SFDC GuestSFDC Guest
Below code coverage screen shot.User-added image
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi SFDC guest, 

Please use these modified code, 

Apex Class : 
 
global class UpdateLastWorkedDate_onContactBatch implements Database.Batchable<sObject>, Schedulable {
     public EmailTemplate et{get;set;}
      
    global DataBase.QueryLocator start(Database.BatchableContext bc){
                       system.debug('>>>>');

        return DataBase.getQueryLocator([select id,owner.email,TR1__Candidate_Status__c,Last_Day_Worked__c,TRSCHED__Compliance_Owner__r.email from contact where Last_Day_Worked__c!=null]);
        }
    global void execute(Database.BatchableContext BC, List<contact> scope)
       {
                      system.debug('>>>>');

       list<contact> conlist=new list<contact>();
       et=[select id,Name FROM EmailTemplate where Name='3monthsgap' Limit 1];
       list<string> to=new list<string>();
       List<Messaging.SingleEmailMessage> mailsList = new List<Messaging.SingleEmailMessage>();

       for(contact c:scope){
               system.debug('>>>>');

        integer i;
        //i=system.today().monthsBetween(c.Last_Day_Worked__c);
        i=c.Last_Day_Worked__c.monthsBetween(system.today());

        system.debug('>>>>'+i);
        if(i==3){
        c.TR1__Candidate_Status__c='InActive';
        conlist.add(c);
        }
        if(i==2)
        {
                       system.debug('>>>>');

        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
               to.add(c.owner.email);
                 to.add(c.TRSCHED__Compliance_Owner__r.email);

                 mail.setTargetObjectId(c.id);
                 mail.setSaveAsActivity(false);
                 mail.setTreatTargetObjectAsRecipient(false);
                 mail.setTemplateId(et.id);
                 //mail.setWhatId(AQ.id);
                 mail.setToAddresses(to);
          mailsList.add(mail);
        
        }
       }
      if(conlist.Size()>0){

       update conlist;
       }
        // Modified by Prosenjit 
		if(mailsList.Size()>0 && Test.IsRunningTest() == false){
                       system.debug('>>>>');

            Messaging.sendEmail(mailsList);
            }  
       
       }   
    
    global void finish(Database.BatchableContext BC){
        }
       global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
    }
    
}

Test Class :
 
public class Test_UpdateLastWorkedDate_onContactBatch {
public static testMethod void test() 
     {
   /*   Profile p = [SELECT Id FROM Profile WHERE Name='system administrator'];
         
    User us = new User(Alias='Admin',Email='test@gamil.com',LastName='Testing',Username='standardus@testorg.com',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id, 
           TimeZoneSidKey='America/Los_Angeles',EmailEncodingKey='UTF-8');
    insert us;*/
   User us = [Select id from User where Id = :UserInfo.getUserId()];
         
    Account acc = new Account(Name = 'test13');
    insert acc;
    // Modifed By Prosenjit 
    List<Contact> conList = new List<Contact>();
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-90), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-60), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
    insert conList;
         
 //     EmailTemplate eT = new EmailTemplate (developerName = 'X3monthsgap', subject='test', FolderId = UserInfo.getUserId(), TemplateType= 'Text', Name = '3monthsgap'); 
     //    insert eT;
   System.runAs(us)
   {
   Test.startTest();
     UpdateLastWorkedDate_onContactBatch obj = new UpdateLastWorkedDate_onContactBatch();
     DataBase.executeBatch(obj); 
         
   Test.stopTest();
   }  
    }
    
}

Explanation : I have marked my modification by 'Modified By Prosenjit' comment. As we cannot send email from test class thats why I have added Test.IsRunningTest() while finally sending mail, not to execute the line while testing via test class. One Contact has also added to with a data which has worked for 2 months. Initially you have created only one test case (one Contact) which has worked for 3 months.

Thanks,
Prosenjit ​
SFDC GuestSFDC Guest
Hi Prosenjit,

Thanks for solution. Now it's 90%. Below code not covered. Please let me know how to cover this.

global void execute(SchedulableContext sc) {
        UpdateLastWorkedDate_onContactBatch b1 = new UpdateLastWorkedDate_onContactBatch();
        ID batchprocessid = Database.executeBatch(b1,200);    
 
Prosenjit Sarkar 7Prosenjit Sarkar 7
Hi,

Modify Your Test Class with this one, 
 
public class Test_UpdateLastWorkedDate_onContactBatch {
public static testMethod void test() 
     {
   /*   Profile p = [SELECT Id FROM Profile WHERE Name='system administrator'];
         
    User us = new User(Alias='Admin',Email='test@gamil.com',LastName='Testing',Username='standardus@testorg.com',LanguageLocaleKey='en_US',LocaleSidKey='en_US',ProfileId = p.Id, 
           TimeZoneSidKey='America/Los_Angeles',EmailEncodingKey='UTF-8');
    insert us;*/
   User us = [Select id from User where Id = :UserInfo.getUserId()];
         
    Account acc = new Account(Name = 'test13');
    insert acc;
    // Modifed By Prosenjit 
    List<Contact> conList = new List<Contact>();
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-90), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
	conList.add(new Contact(LastName = 'One', Last_Day_Worked__c=system.today().adddays(-60), Email ='test.user@gmail.com',  TR1__Candidate_Status__c ='DNU', TRSCHED__Compliance_Owner__c=us.id,  AccountId=acc.id));
    insert conList;
         
 //     EmailTemplate eT = new EmailTemplate (developerName = 'X3monthsgap', subject='test', FolderId = UserInfo.getUserId(), TemplateType= 'Text', Name = '3monthsgap'); 
     //    insert eT;
   System.runAs(us)
   {
   Test.startTest();
     UpdateLastWorkedDate_onContactBatch obj = new UpdateLastWorkedDate_onContactBatch();
     DataBase.executeBatch(obj); 
     
		// code to test schedules
		UpdateLastWorkedDate_onContactBatch schClass = new UpdateLastWorkedDate_onContactBatch();
		String sch = '0 0 23 * * ?'; 
		system.schedule('Test Territory Check', sch, schClass);
		
   Test.stopTest();
   }  
    }
    
}

If this solution works please make this as a best answer for future searches.

Thanks,
Prosenjit​
This was selected as the best answer
SFDC GuestSFDC Guest
Thank you so much Prosenjit. Very Appreciative.