Sub topic 10
Testing a Batch Class
This chapter assumes you can write Apex classes and SOQL, know the basic governor limits, and have already written the AccountRatingBatch class from the earlier chapters. It covers how to test a batch job so that it passes deployment checks and catches real bugs.
How batch jobs run in tests
A batch job normally runs asynchronously, after your code has finished. A test cannot wait for that. Apex solves this with Test.startTest() and Test.stopTest(). Any batch job started between these two calls runs synchronously when Test.stopTest() is reached. After that line, the job has finished and you can query the results.
A test also runs only one execute call. Salesforce limits a test to one batch of records, so keep your test data within the batch size you pass to Database.executeBatch. With a scope of 200, create 200 records or fewer.
A basic test
@IsTest
private class AccountRatingBatchTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 150; i++) {
accts.add(new Account(Name = 'Test ' + i));
}
insert accts;
}
@IsTest
static void setsRatingOnAllAccounts() {
Test.startTest();
Database.executeBatch(new AccountRatingBatch(), 200);
Test.stopTest();
System.assertEquals(150, [SELECT COUNT() FROM Account WHERE Rating = 'Cold']);
}
}The @TestSetup method creates 150 accounts with no rating. The test starts the job, forces it to finish with Test.stopTest(), and then asserts on the data.
What to assert
Check the outcome of the job, not just that it ran without errors.
- Assert that the records that should change did change.
- Add a record that should not match the query, such as an account that already has a rating, and assert that it is untouched.
- If you use
Database.Statefulcounters, run the batch instance directly and check them. Keep a reference to the instance before you pass it toexecuteBatch.
@IsTest
static void countsSuccesses() {
AccountRatingBatch job = new AccountRatingBatch();
Test.startTest();
Database.executeBatch(job, 200);
Test.stopTest();
System.assertEquals(150, job.succeeded);
System.assertEquals(0, job.failed);
}This works because the class implements Database.Stateful, so the field values are kept across calls.
Common errors
| Symptom | Cause | Fix |
|---|---|---|
| Assertions see unchanged data | The query ran before `Test.stopTest()` | Move the query after `Test.stopTest()` |
| "Too many batch jobs" or only part of the data processed | Test data larger than one batch | Use at most one batch of records |
| Callout error in `execute` | Real callouts are not allowed in tests | Use `Test.setMock` with an `HttpCalloutMock` |
| Chained job does not run | Batch jobs started from `finish` do not run in tests | Test `finish` logic separately |
Testing failures
To cover the error path, create records that will fail the update, for example by adding a validation rule or a required field that your test data leaves empty. Then assert that failed is greater than zero and that the valid records were still saved. This only works if the batch uses Database.update(scope, false).
Exercise
Why must the assertions in a batch test come after Test.stopTest(), and why should the test data stay within one batch size?
Show answer
The batch job runs synchronously only when Test.stopTest() is reached, so the data has not changed before that line. A test runs only a single execute call, so records beyond the first batch would not be processed and assertions on them would fail.