+ Start a Discussion
Ishan Singh 1Ishan Singh 1 

how to write a test class for batch class and can anyone suggest video link from where I can learn

global class AgeUpdate implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext bc)

    {

    return Database.getQueryLocator([SELECT dateOfBirth__c,Id,Status FROM Lead WHERE Status = 'Unqualified' AND dateOfBirth__c = TODAY]);

   }

     global void execute(Database.BatchableContext bc, List<Lead> scope)

   {

      for(Lead l: scope)

        {

            l.Age__c = l.Current_Age__c;

        }

            update scope;
       
    }
    
     global void finish(Database.BatchableContext bc)
     {}

}
 
Best Answer chosen by Ishan Singh 1
SUCHARITA MONDALSUCHARITA MONDAL

Hi Ishan,
You can go for something as below:
@isTest
public class testClass{
    @isTest
    public static void test1(){
        List<Lead> leadList = new List<Lead>();
        for(int i=0;i<200;i++){
            Lead ld = new Lead();
            ld.lastname = 'test'+i;
            ld.dateOfBirth__c = TODAY;
            Status = Unqualified;
            leadList.add(ld);    
        }
        insert leadList;
        Test.startTest();
        Database.executeBatch(new AgeUpdate());
        Test.stopTest();
    }
}

P.S. - Link to writing test classes:

https://apexcoder.com/2016/11/08/how-to-write-test-class-for-batch-apex-in-salesforce/


Thanks,
Sucharita

All Answers

SUCHARITA MONDALSUCHARITA MONDAL

Hi Ishan,
You can go for something as below:
@isTest
public class testClass{
    @isTest
    public static void test1(){
        List<Lead> leadList = new List<Lead>();
        for(int i=0;i<200;i++){
            Lead ld = new Lead();
            ld.lastname = 'test'+i;
            ld.dateOfBirth__c = TODAY;
            Status = Unqualified;
            leadList.add(ld);    
        }
        insert leadList;
        Test.startTest();
        Database.executeBatch(new AgeUpdate());
        Test.stopTest();
    }
}

P.S. - Link to writing test classes:

https://apexcoder.com/2016/11/08/how-to-write-test-class-for-batch-apex-in-salesforce/


Thanks,
Sucharita

This was selected as the best answer
Ishan Singh 1Ishan Singh 1
Thank you!