Sub topic 10
Testing a Batch Class
This chapter assumes you can write Apex classes and SOQL, know the basics of @IsTest classes, and have read the earlier chapters on the start, execute and finish methods. Here you will learn how to run a batch job inside a test, what Salesforce does differently for batch jobs under test, and the errors that most often break batch tests.
Why batch tests need special care
A batch job runs asynchronously. When you call Database.executeBatch, Salesforce queues the job and returns right away. In a normal run, the work happens later.
A test cannot wait for a queued job in the usual sense. Salesforce solves this with Test.startTest() and Test.stopTest(). Any asynchronous work you start between these two calls runs synchronously when Test.stopTest() is called. After stopTest, the job has finished and you can query the results.
Without this pair, your assertions run before the job has done anything, and the test fails or, worse, passes for the wrong reason.
The basic test
This test targets the AccountRatingBatch class from earlier in the tutorial. It creates data, runs the batch between startTest and stopTest, and then checks the result.
@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']);
}
}Points to notice:
@TestSetupcreates the records once, and each test method starts with a fresh copy of them.- The batch size is 200 and there are 150 records, so the whole data set fits in one
executecall. - The assertion reads the database after
stopTest. Reading earlier would show the unchanged data.
The one-execute rule
A test can run only one execute call of a batch job. If the query returns more records than the batch size, the extra records are not processed in the test.
This rule shapes how you write the test:
- Keep the number of test records at or below the batch size you pass to
executeBatch. - Do not try to test "millions of records" in a test. You cannot, and you do not need to.
- Test the chunking logic through small, focused cases instead, for example a batch size of 2 with 2 records.
If you create 500 records and pass a batch size of 200, only the first 200 records are handled. An assertion on all 500 would then fail, and the cause is easy to miss.
What runs and what does not
The following table shows how each part of the batch job behaves in a test.
| Part | Behaviour in a test |
|---|---|
| `start` | Runs once when the job begins. |
| `execute` | Runs once, for the first chunk of records only. |
| `finish` | Runs after `execute`, before `stopTest` returns. |
| Chained `executeBatch` in `finish` | Not allowed to start a second job in a test. |
The last row matters. If finish calls Database.executeBatch to chain another job, the call can throw an error when it runs under test. The fix is to check Test.isRunningTest() before chaining, so the chain is skipped during tests.
public void finish(Database.BatchableContext bc) {
if (!Test.isRunningTest()) {
Database.executeBatch(new ContactCleanupBatch(), 200);
}
}Use this guard sparingly. It means the chaining line itself is never covered by a test. Test the second job on its own in a separate test method.
Following the flow of a test
The diagram shows what happens between startTest and stopTest.
Giving the job a fresh set of limits
Test.startTest() also resets governor limits for the code that follows. The code in @TestSetup and the code before startTest counts against one set of limits. Everything between startTest and stopTest gets a new set.
This is useful for batch tests. Creating test data can consume many DML rows. The reset means the batch job itself is measured against its own limits, as it would be in production.
Testing state with Database.Stateful
If your batch implements Database.Stateful, its counters survive between execute calls. In a test you only get one execute call, so you can check the counters only for that one chunk.
You can still verify the logic, because the instance you pass to executeBatch is the object whose fields are kept. Keep a reference to it and read the fields after stopTest.
@IsTest
private class StatefulBatchTest {
@IsTest
static void countsSucceededRecords() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 10; i++) {
accts.add(new Account(Name = 'State ' + i));
}
insert accts;
AccountRatingBatch job = new AccountRatingBatch();
Test.startTest();
Database.executeBatch(job, 200);
Test.stopTest();
Integer rated = [SELECT COUNT() FROM Account WHERE Rating = 'Cold'];
System.assertEquals(10, rated);
}
}Be careful here. Salesforce serializes a stateful batch between chunks, so the object you hold in the test may not show the final field values. The safest check is to assert on saved records, as above. If you must check a counter, write it to a record in finish and read that record.
Testing partial failures
The error handling chapter used Database.update(scope, false) so valid records save while failed ones are logged. A good test proves this behaviour. Create a mix of good and bad records and check that the good ones still save.
A reliable way to force a failure is a validation rule or a required field that only some records break. In a test, you can also make a record fail by creating a state the batch cannot handle, such as a record that a trigger rejects.
Whatever the method, assert on two things:
- The valid records changed.
- The invalid records stayed unchanged.
This confirms that one bad record did not roll back the whole chunk.
Testing callouts
Tests cannot make real HTTP callouts. If a batch class implements Database.AllowsCallouts, you must supply a mock response with Test.setMock. Set the mock before Test.startTest().
@IsTest
private class CalloutBatchTest {
private class MockOk implements HttpCalloutMock {
public HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{"ok":true}');
return res;
}
}
@IsTest
static void runsWithMockedCallout() {
insert new Account(Name = 'Callout test');
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
Database.executeBatch(new AccountSyncBatch(), 200);
Test.stopTest();
System.assertEquals(1, [SELECT COUNT() FROM Account]);
}
}Here AccountSyncBatch stands for any batch class of yours that implements Database.AllowsCallouts. Without the mock, the test fails with an error saying callouts are not allowed from tests.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertions see unchanged data | Assertions run before `stopTest`, or no `startTest`/`stopTest` pair | Wrap `executeBatch` in the pair and assert afterwards |
| Only part of the records changed | More records than the batch size | Keep test records at or below the batch size |
| Error when `finish` chains a job | A second `executeBatch` runs under test | Guard with `Test.isRunningTest()` |
| "Methods defined as TestMethod do not support Web service callouts" | No mock set | Call `Test.setMock` before `startTest` |
| Test passes but covers little | Only the happy path is tested | Add cases for empty scope and failed records |
Test the empty case
Add one test where the query returns no records. A batch job with nothing to process must finish without errors. This confirms that start and finish handle an empty set, which happens often in production on quiet days.
@IsTest
private class EmptyBatchTest {
@IsTest
static void finishesWithNoRecords() {
Test.startTest();
Id jobId = Database.executeBatch(new AccountRatingBatch(), 200);
Test.stopTest();
AsyncApexJob job = [
SELECT Status, NumberOfErrors FROM AsyncApexJob WHERE Id = :jobId
];
System.assertEquals('Completed', job.Status);
System.assertEquals(0, job.NumberOfErrors);
}
}This test also shows how to read the AsyncApexJob record, which is a quick way to confirm that a job ended cleanly.
Testing the schedule
To test a Schedulable class, call System.schedule between startTest and stopTest. The scheduled job runs when stopTest is called, and it starts the batch. The cron expression only needs to be valid, because the job runs at once under test.
@IsTest
private class NightlyJobTest {
@IsTest
static void schedulesTheBatch() {
Test.startTest();
Id cronId = System.schedule(
'Test nightly rating', '0 0 2 * * ?', new NightlyAccountRatingJob()
);
Test.stopTest();
CronTrigger ct = [SELECT CronExpression FROM CronTrigger WHERE Id = :cronId];
System.assertEquals('0 0 2 * * ?', ct.CronExpression);
}
}Practical guidelines
- Always pair
startTestandstopTestaroundexecuteBatch. - Keep test data within one batch size.
- Assert on saved records, not on in-memory objects.
- Cover success, partial failure, and empty input.
- Mock callouts before
startTest. - Guard chaining in
finishand test the chained job separately.
Exercise
A batch class uses a batch size of 100. Your test inserts 250 accounts, runs the job between startTest and stopTest, and asserts that all 250 were updated. The assertion fails and shows only 100 updated. Why does this happen, and how do you fix the test?
Show answer
A test runs only one execute call, so only the first chunk of 100 records is processed. Fix the test by inserting no more records than the batch size (for example, 100 or fewer), or by passing a batch size of at least 250 to executeBatch in the test. Then the whole data set fits in the single execute call.
Exercise
Your finish method calls Database.executeBatch to start a second job, and a test for the first job throws an error. What change makes the test pass, and what should you add to keep the second job covered?
Show answer
Wrap the chained call in if (!Test.isRunningTest()) so it is skipped under test. Then write a separate test that runs the second batch class directly between startTest and stopTest.