Sub topic 8
Testing Batch Apex
This chapter assumes you can write a basic @IsTest class, know what Database.Batchable does, and understand that Test.startTest and Test.stopTest open and close a test window. Here you will test a batch job and learn why its test data must stay small.
How a batch job behaves in a test
In production, Batch Apex splits records into scopes and runs execute once per scope, each in its own transaction. In a test, Test.stopTest runs the job synchronously, but only one execute call happens. Any records beyond the first scope are never processed.
This leads to a rule: keep your test data within a single scope. The default scope size is 200 records, and the maximum is 2,000. If you pass 200 to Database.executeBatch and insert 5 records, one execute call covers all of them.
A complete example
The batch class below sets a description on every account that has none. The test inserts five accounts, runs the job inside the window, and counts the processed records afterwards.
public class AccountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account WHERE Description = null');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Description = 'Batch processed';
}
update scope;
}
public void finish(Database.BatchableContext bc) {}
}
@IsTest
private class AccountBatchTest {
@IsTest
static void batchProcessesAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Batch ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Integer processed = [SELECT COUNT() FROM Account WHERE Description = 'Batch processed'];
Assert.areEqual(5, processed);
}
}What each part does
- The test inserts the accounts before
Test.startTest. This keeps setup work out of the window and its fresh governor limits. Database.executeBatchinside the window only queues the job.Test.stopTestrunsstart, oneexecutecall andfinish, all synchronously.- The test re-queries the records after
stopTest. The in-memoryaccountslist is stale, because the batch updated the database copies.
Common mistakes
| Mistake | Result | Fix |
|---|---|---|
| Asserting before `Test.stopTest` | The job has not run, so the assertion sees unchanged data | Assert after `stopTest` |
| Inserting more than one scope of data | Only the first scope is processed | Keep data within the scope size |
| Checking the in-memory list | Values look unchanged | Re-query with SOQL |
| Calling `executeBatch` outside the window | The job may not run before the test ends | Call it between `startTest` and `stopTest` |
If your execute method makes callouts, add a mock with Test.setMock before startTest. Chapter content on mocks covers this in detail.
To test batch logic with more than one scope, move the work into a plain method and call it directly with a list you build yourself.
Exercise
A test inserts 500 accounts, calls Database.executeBatch(new AccountBatch(), 200) between startTest and stopTest, then asserts that 500 accounts have the description 'Batch processed'. The assertion fails. Why, and what would you change?
Show answer
A test runs only one execute call, so only the first 200 records are processed. Insert 200 or fewer accounts and assert that count. To test logic across larger volumes, call the processing code directly from the test.