Sub topic 8
Testing Batch Apex
This chapter assumes you can write a basic @IsTest class, insert records with DML, and recognize the Database.Batchable interface. It also assumes you've read the earlier chapters on the test window and on async work running synchronously at Test.stopTest().
What changes for Batch Apex
Batch Apex splits a large job into scopes and runs each scope in its own transaction. In production, a job over 10,000 records and a batch size of 200 produces 50 execute calls. A test can't wait for that. It also shouldn't need to, because the logic you want to verify lives in a single execute call.
Salesforce handles this with two rules for tests:
Database.executeBatchqueues the job inside the test window, and the job runs whenTest.stopTest()is reached.- Only one
executeinvocation runs. Records beyond the first scope are never processed.
The start method runs once, then execute runs for the first scope, then finish runs. All three complete before Test.stopTest() returns.
The batch class under test
The examples use this batch class. It selects accounts whose Description is empty and fills it in.
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) {}
}A basic batch test
Create the data first, outside the test window. Then run the batch between startTest and stopTest, and query the results afterward.
@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);
}
}Three details matter here:
- The scope size passed to
executeBatchis 200, the maximum. Five records fit in one scope, so every record is processed. - The test doesn't see existing org data. Tests run with
SeeAllData=falseby default, so the query locator only finds the five accounts the test created. - The assertion runs after
stopTest. Before that point,start,execute, andfinishhaven't run, so every account still has a nullDescription.
Keep data within one scope
Because only the first execute runs, the number of records you insert should not exceed the scope size. Suppose you insert 250 accounts and use a scope of 200. Only 200 are processed, and an assertion that expects 250 fails.
Two ways to deal with this:
- Keep the test data small. Five to ten records are enough to prove the logic.
- Use a smaller scope on purpose, for example
Database.executeBatch(new AccountBatch(), 2), and assert that exactly two records were processed. This confirms that the scope size parameter is respected.
@IsTest
private class AccountBatchScopeTest {
@IsTest
static void onlyFirstScopeIsProcessed() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 10; i++) {
accounts.add(new Account(Name = 'Scope ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountBatch(), 2);
Test.stopTest();
Integer processed = [SELECT COUNT() FROM Account WHERE Description = 'Batch processed'];
Assert.areEqual(2, processed, 'Only one execute call of two records should have run');
}
}Use a test like this to document the limit, not as a pattern for real coverage. Production behavior across many scopes is not exercised by tests, so keep execute free of assumptions about which scope it is in.
Negative cases
A good batch test also checks which records are left alone. Add a record the query should skip and assert that it is unchanged.
@IsTest
private class AccountBatchFilterTest {
@IsTest
static void skipsAccountsWithDescription() {
Account fresh = new Account(Name = 'Fresh');
Account done = new Account(Name = 'Done', Description = 'Original');
insert new List<Account>{ fresh, done };
Test.startTest();
Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
Assert.areEqual('Batch processed', [SELECT Description FROM Account WHERE Id = :fresh.Id].Description);
Assert.areEqual('Original', [SELECT Description FROM Account WHERE Id = :done.Id].Description);
}
}Checking the job itself
Database.executeBatch returns the job Id. After stopTest, you can query AsyncApexJob to confirm the job finished without errors.
@IsTest
private class AccountBatchJobTest {
@IsTest
static void jobCompletesWithoutErrors() {
insert new Account(Name = 'Job check');
Test.startTest();
Id jobId = Database.executeBatch(new AccountBatch(), 200);
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors, JobItemsProcessed
FROM AsyncApexJob
WHERE Id = :jobId
];
Assert.areEqual('Completed', job.Status);
Assert.areEqual(0, job.NumberOfErrors);
Assert.areEqual(1, job.JobItemsProcessed);
}
}Treat this as a supplement to the data assertion, not a replacement. A job can complete while having processed the wrong records.
Testing `execute` directly
If you want to test the logic of execute without the queue, call it as a normal method. Pass null for the BatchableContext if your code doesn't use it.
@IsTest
private class AccountBatchDirectTest {
@IsTest
static void executeSetsDescription() {
Account a = new Account(Name = 'Direct');
insert a;
List<Account> scope = [SELECT Id FROM Account WHERE Id = :a.Id];
new AccountBatch().execute(null, scope);
Assert.areEqual('Batch processed', [SELECT Description FROM Account WHERE Id = :a.Id].Description);
}
}This has no startTest or stopTest because nothing is asynchronous. It is faster to write and good for branching logic. It does not check the query in start, so keep at least one test that goes through executeBatch.
Batches that keep state
A class that implements Database.Stateful keeps its member variables between execute calls. In a test, keep a reference to the batch instance and read its fields after stopTest.
public class AccountCountBatch implements Database.Batchable<SObject>, Database.Stateful {
public Integer processedCount = 0;
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator('SELECT Id FROM Account');
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
processedCount += scope.size();
}
public void finish(Database.BatchableContext bc) {}
}
@IsTest
private class AccountCountBatchTest {
@IsTest
static void countsProcessedRecords() {
insert new List<Account>{
new Account(Name = 'One'),
new Account(Name = 'Two'),
new Account(Name = 'Three')
};
AccountCountBatch batch = new AccountCountBatch();
Test.startTest();
Database.executeBatch(batch, 200);
Test.stopTest();
Assert.areEqual(3, batch.processedCount);
}
}Without Database.Stateful, each execute call would get a fresh copy of the instance, and the test's reference would not see the changes.
Governor limits and the batch
Each execute call has its own set of governor limits, as in production. Setup work before startTest shares the limits of the test method itself. The batch's work runs in its own context at stopTest, so a heavy fixture insert doesn't eat into the budget of the job.
Common mistakes
| Mistake | Symptom | Fix |
|---|---|---|
| Asserting before `stopTest` | Records unchanged, assertion fails | Move assertions after `Test.stopTest()` |
| Inserting more records than the scope size | Fewer records processed than expected | Keep records at or below the scope size |
| Calling `executeBatch` twice in one test | Second run fails or is skipped | Test each run in its own test method |
| Using stale in-memory records | Assertion sees old values | Re-query by Id after `stopTest` |
| Callout in `execute` without a mock | "Methods defined as TestMethod do not support Web service callouts" | Add `Database.AllowsCallouts` and call `Test.setMock` before `startTest` |
Exercises
Exercise
A batch class has a scope size of 100. A test inserts 150 accounts, calls Database.executeBatch(new MyBatch(), 100) between startTest and stopTest, and asserts that all 150 were updated. Why does the assertion fail, and what are two ways to fix the test?
Show answer
In a test, only one execute call runs, so only the first scope of 100 records is processed and 50 are untouched. Fix it by inserting 100 or fewer records so everything fits in one scope, or by changing the assertion to expect 100 updated records. Both fixes depend on the one-execute limit.
Exercise
A test for a Database.Stateful batch asserts on batch.processedCount, but the value is 0 after stopTest. The test calls Database.executeBatch(new CountBatch(), 200) with a new instance created inline. What is the likely cause?
Show answer
The test never kept a reference to the instance that ran. Create the instance in a variable, pass that variable to executeBatch, and read its field after stopTest. Without the reference, the test reads a different object (or none at all) and sees the default value.