Sub topic 3
Testing a Batch Class
Assume you know Apex classes, SOQL, DML, and basic governor limits. A batch test should verify both the records changed and the job's asynchronous behavior.
Test the batch
Use Test.startTest() and Test.stopTest() around Database.executeBatch(). Test.stopTest() runs the queued batch before assertions. Keep the test data within one batch.
@IsTest
private class AccountRatingBatchTest {
@IsTest
static void updatesAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 10; i++) {
accounts.add(new Account(Name = 'Test ' + i));
}
insert accounts;
Test.startTest();
Database.executeBatch(new AccountRatingBatch(), 200);
Test.stopTest();
System.assertEquals(
10,
[SELECT COUNT() FROM Account WHERE Rating = 'Cold']
);
}
}Monitor and schedule jobs
Query AsyncApexJob with the job ID to inspect status, progress, and errors. Call System.abortJob(jobId) when an active job must stop.
A class that implements Schedulable can start a batch on a cron schedule:
public class NightlyRatingJob implements Schedulable {
public void execute(SchedulableContext context) {
Database.executeBatch(new AccountRatingBatch(), 200);
}
}
System.schedule(
'Nightly account rating',
'0 0 2 * * ?',
new NightlyRatingJob()
);Callouts, queues, and chaining
A batch that calls an external service must implement Database.AllowsCallouts. Keep callouts in execute, handle timeouts, and store enough information to retry safely.
Salesforce runs only a limited number of batch jobs concurrently. Additional jobs wait in the Flex Queue, which can hold up to 100 batch jobs. Avoid submitting duplicate jobs and choose a scope size that respects callout and governor limits.
A batch can start another batch from finish. This creates a controlled sequence, but excessive chaining can delay other work.
Design and choose the right tool
For millions of records, use selective queries, small queried fields, bounded work per scope, partial failure handling, and idempotent updates. An idempotent job can run again without corrupting data.
Batch Apex fits work that needs independent transactions and progress tracking. Queueable Apex fits smaller, chained jobs with complex parameters. Bulk API fits large data loads from outside Salesforce. Synchronous Apex fits only small, immediate operations.
Exercise
Why does a batch test call Test.stopTest() before checking records?
Show answer
It forces the queued asynchronous work to complete before the assertions run.