We should always test batch class with good amount of data (minimum 200 records) in our test class. Here is the example of batch apex testing.
In below code, we are updating name of all accounts with “Updated” keyword in the last of account name.
Batch Class:
global class AccountUpdate implements Database.Batchable { global Database.QueryLocator start(Database.BatchableContext BC){ return Database.getQueryLocator('Select Id, Name From Account'); } global void execute(Database.BatchableContext BC, List scope){ for(Account a: scope){ a.Name += ' Updated'; } update scope; } global void finish(Database.BatchableContext BC){}
In below code, we are testing above batch class by creating 200 test accounts to make sure that Account Name gets updated by batch apex correctly.
Test Class:
@isTest private class accListountUpdate { static testmethod void test() { // Create test accounts to be updated // by the batch job. Account[] accList = new List(); for (Integer i=0;i<200;i++) { Account m = new Account(Name = 'Account ' + i); accList.add(m); } insert accList; Test.startTest(); AccountUpdate c = new AccountUpdate(); Database.executeBatch(c); Test.stopTest(); // Verify accounts updated Account[] accUpdatedList = [SELECT Id,Name FROM Account]; System.assert(accUpdatedList[0].Name.Contains('Updated')); } }
Note: – As best practice, you must execute the batch class between Test.StartTest() and Test.StopTest().
We can also load data from static resource to create Accounts using the following syntax.
List ls = Test.loadData(Account.sObjectType, ‘myResource’);
You must store the static resource (e.g. account.csv) under Salesforce static resources. The supported types of files are text/csv, application/vnd.ms-excel, application/octet-stream, text/plain.
For more information :-
Author:
![]() |
AJOMON JOSEPH Senior Salesforce Architect ![]() ![]() ![]() ![]() |