How to write test class for Batch Apex in Salesforce ?

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:

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);
insert accList;

AccountUpdate c = new AccountUpdate();

// Verify accounts updated
Account[] accUpdatedList = [SELECT Id,Name FROM Account];

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/, application/octet-stream, text/plain.

For more information :-

Adding a Batch Apex Class

Batch Apex Testing


Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog
email Email me

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s