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:

@isTest
private class accListountUpdate {

static testmethod void test() {

// Create test accounts to be updated
// by the batch job.

Account[] accList = new List<Account>();
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 :-

Adding a Batch Apex Class

Batch Apex Testing

Author:

Ajomon Joseph AJOMON JOSEPH
Senior Salesforce Architect
In Connect me on LinkedIn
twitter Follow me on Twitter @apexcoder
blogger Subscribe to my blog https://apexcoder.com
email Email me ajomon@apexcoder.com

Leave a Reply

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

WordPress.com Logo

You are commenting using your WordPress.com 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