+ Start a Discussion
Avinash RaviAvinash Ravi 

Need help writing a test class for batch class

All,

I have this batch class that I'm using to send emails to specific people.. But I'm not sure how I'm supposed to write a test class for it. I've done it for simple insert and update operations but I have no idea where to start from with this. Can someone help me out?

Thanks in Advance.
global class sendEmailtoVolntr implements schedulable,Database.Batchable<sObject>,Database.Stateful
{
    global String Query = null;

    global sendEmailtoVolntr (){
  
       Query='Select Id,Name,For_Centre__c,For_Date__c,Leap_Centre__c,Leap_Centre__r.Name,Send_Email__c,Short_Description__c,Uploaded_By__c from Leap_Weekly_Curriculum__c where Send_Email__c = FALSE and For_Date__c >= TODAY';
   
    }
    
    global Database.QueryLocator start(Database.BatchableContext BC){
        return Database.getQueryLocator(Query);
    }
    
    global void execute(SchedulableContext SC){
        sendEmailtoVolntr sendEmail= new sendEmailtoVolntr ();
        database.executebatch(sendEmail,1);
     }
    
    global void execute(Database.BatchableContext BC, List<sObject> scope){
    
        List<Attachment> attachments = new List<Attachment> ();
        Map<Id,Attachment> attachmentId = new Map<Id,Attachment> ();
        Set<Id> LeapIds = new Set<Id> ();
        List<Leap_Weekly_Curriculum__c> leapCurrilist = new List<Leap_Weekly_Curriculum__c> ();
        List<Leap_Weekly_Curriculum__c> updateLeapList = new List<Leap_Weekly_Curriculum__c> ();
    
        for(sObject so : scope){ 
    
            Leap_Weekly_Curriculum__c leapCurri= (Leap_Weekly_Curriculum__c)so;
            LeapIds.add(leapcurri.Id);
            leapCurrilist.add(leapCurri);
           } 
        attachments = [SELECT Id,ParentId, Name, Body, ContentType FROM Attachment WHERE Parentid IN :LeapIds];
          //Assuming that there will be only one attachment for each Leap Curriculum record           
        for(Attachment att : attachments)
        {
            attachmentId.put(att.ParentId,att);
        }
        attachments.clear();
        
        for(Leap_Weekly_Curriculum__c LWC: leapCurrilist)
        {
            Messaging.SingleEmailMessage email = new Messaging.SingleEmailMessage();
            List<Messaging.SingleEmailMessage> theEmails = new List<Messaging.SingleEmailMessage> ();
            List<Messaging.EmailFileAttachment> emailAttachments = new List<Messaging.EmailFileAttachment>();
            Messaging.EmailFileAttachment efa = new Messaging.EmailFileAttachment();
            List<String> toAddresses = new List<String> ();
            String emailErrorReport = null;
            
            for(Volunteers__c vol: [Select Email__c from Volunteers__c WHERE Centre_Allocation__c includes(:LWC.Leap_Centre__r.Name)])
            toAddresses.add(vol.Email__c);
            //List<Volunteers__c> volListTeamp = [Select Email__c from Volunteers__c WHERE Centre_Allocation__c includes(:LWC.Leap_Centre__r.Name)];
            system.debug(toAddresses);
    
            efa.setFileName(attachmentId.get(LWC.Id).Name);
            efa.setBody(attachmentId.get(LWC.Id).Body);
            efa.setContentType(attachmentId.get(LWC.Id).ContentType);
            emailAttachments.add(efa);
            
            if(emailAttachments.size() > 0)
            {
                email.setToAddresses(toAddresses);
                email.setSubject('test');
                email.setPlainTextBody('For Leap Curriculum : ID -  ' + LWC.Id + ' Name - ' + LWC.Name + ' Short Description - ' + LWC.Short_Description__c + '.');
                email.setFileAttachments(emailAttachments);
                theEmails.add(email);
            }
            
            if(theEmails.size() > 0)
            {
                
                Messaging.SendEmailResult[] results = Messaging.sendEmail(theEmails,false);
                Messaging.SendEmailError[] errors = new List<Messaging.SendEmailError>();
                
                for( Messaging.SendEmailResult currentResult : results ) 
                {
                    errors = currentResult.getErrors();
                    if( null != errors ) 
                    {
                        for( Messaging.SendEmailError currentError : errors ) 
                        {
                            emailErrorReport = emailErrorReport + '(' +  currentError.getStatusCode() + ')' + currentError.getMessage() + '\r' ;
                        }
                    }
                }
    
                system.debug('error : ' + emailErrorReport);

             }

            System.debug('HEAP_SIZE Used:'+ Limits.getHeapSize()); 
            
            if(emailErrorReport != null){
                break;
            }
            else
            {
                LWC.send_EMail__c = TRUE;
                updateLeapList.add(LWC);  
            }
            
            if(updateLeapList.size()>0)
            update updateLeapList;
            
            if(emailErrorReport != null){
                System.abortJob(BC.getJobId()); 
                List<sObject> so = scope;
                Leap_Weekly_Curriculum__c lwcr= (Leap_Weekly_Curriculum__c )so[0];          
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                String[] toAddresseser = new String[] {'rahmeshms@outlook.com'};
                mail.setToAddresses(toAddresseser);
                mail.setSubject('Email Job is aborted'); 
                mail.setPlainTextBody('The send email job is aborted due to Leap Curriculum : '+lwcr.Name+' '+lwcr.Short_Description__c+ ' '+lwcr.Id+ 'Please check the error report and take action accordingly.\n\n\t Error - '+emailErrorReport);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }
       } 
       
   }
global void finish(Database.BatchableContext BC){

    }


    
        }

 
ClintLeeClintLee
You'll need to write a test class that first creates the data you need for testing and then executes the batch.

Here is a general framework:
 
@istest
public with sharing class Test_sendEmailtoVolntr
{
    /**
     *  Create your test data here.
     *  This method will get executed before each test method.
     *
    **/
    @TestSetup
    static void setupData()
    {
        // create your Leap_Weekly_Curriculum__c records
        // create your Attachments
        // create your Volunteers__c records
    }

    static testmethod void testOne()
    {
        Test.startTest();
     
        // execute the batch class
        sendEmailtoVolntr batch = new sendEmailtoVolntr();
        Database.executeBatch(batch,1);

         Test.stopTest();  // this will force the batch class to finish

         // make assertions to ensure logic executed appropriately
    }

   /**
    *  Test the schedulable method.
    *
    **/
    static testmethod void testTwo()
    {
        Test.startTest();

        // schedule the job
        Id jobId = System.schedule('Send Email to Volunteers', '0 0 0 * * ? *', new sendEmailtoVolntr());

        Test.stopTest();

        // ensure the job was scheduled successfully
        System.assertNotEquals(null, jobId);
    }
}

Hope that helps,

Clint