Sub topic 13
Testing Queueable, Batch and future code
This chapter assumes you can write a basic test class with @isTest, Assert methods and Test.startTest/Test.stopTest, and that you have written at least one Queueable, Batch or @future class. It covers how asynchronous Apex behaves inside a test and how to assert on its results.
Why async code needs special handling
Production async Apex runs later, in a separate transaction, on a schedule the platform chooses. A test cannot wait for that. The platform therefore changes the rules inside a test:
- Async work started between
Test.startTest()andTest.stopTest()is held back. - When
Test.stopTest()runs, the platform executes all of that work synchronously and finishes it before the next line of your test. - Each async job gets its own fresh set of governor limits, as it would in production.
This is why Test.startTest/Test.stopTest is not optional for async tests. If you enqueue a job outside that pair, you have no reliable point at which the job has finished.
Testing a Queueable
This Queueable labels accounts as high value or standard, based on revenue.
public with sharing class AccountLabelJob implements Queueable {
private final Set<Id> accountIds;
public AccountLabelJob(Set<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext ctx) {
List<Account> accounts = [
SELECT Id, AnnualRevenue FROM Account WHERE Id IN :accountIds
];
for (Account a : accounts) {
Boolean high = a.AnnualRevenue != null && a.AnnualRevenue > 1000000;
a.Description = high ? 'High value' : 'Standard';
}
update accounts;
}
}The test inserts data first, enqueues the job inside the start/stop pair, and then queries fresh records. The in-memory Account objects in your test are not updated by the job, so you must re-query.
@isTest
private class AccountLabelJobTest {
@isTest
static void labelsAccountsByRevenue() {
Account big = new Account(Name = 'Big', AnnualRevenue = 5000000);
Account small = new Account(Name = 'Small', AnnualRevenue = 100);
insert new List<Account>{ big, small };
Test.startTest();
System.enqueueJob(new AccountLabelJob(new Set<Id>{ big.Id, small.Id }));
Test.stopTest();
Map<Id, Account> result = new Map<Id, Account>(
[SELECT Id, Description FROM Account WHERE Id IN :new Set<Id>{ big.Id, small.Id }]
);
Assert.areEqual('High value', result.get(big.Id).Description, 'Big account should be labelled');
Assert.areEqual('Standard', result.get(small.Id).Description, 'Small account should be standard');
}
}Note that each assertion checks a specific record. Asserting only that "two records have a description" would pass even if the labels were swapped.
Chained Queueables
A Queueable can enqueue another Queueable from its execute method. Salesforce does not allow that chaining inside a test, and the second System.enqueueJob throws an error. The usual workaround is to guard the chained call:
- Wrap the call in
if (!Test.isRunningTest()). - Test the first job's work in one test, and test the next job by enqueuing it directly in another test.
Using Test.isRunningTest() leaves one line uncovered, so treat that as an accepted gap rather than a reason to restructure the code.
Testing Batch Apex
A Batch class processes records in chunks. In a test, only one execute call runs, so the number of records the job sees is limited to the scope you pass to Database.executeBatch. Keep the test data at or below that scope size.
public with sharing class UnratedAccountBatch implements Database.Batchable<SObject> {
public Database.QueryLocator start(Database.BatchableContext bc) {
return Database.getQueryLocator([SELECT Id FROM Account WHERE Rating = null]);
}
public void execute(Database.BatchableContext bc, List<Account> scope) {
for (Account a : scope) {
a.Rating = 'Cold';
}
update scope;
}
public void finish(Database.BatchableContext bc) {
}
}The test creates records that should be processed and records that should be left alone. It then asserts on both groups.
@isTest
private class UnratedAccountBatchTest {
@isTest
static void ratesOnlyUnratedAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 150; i++) {
accounts.add(new Account(Name = 'Unrated ' + i));
}
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Rated ' + i, Rating = 'Hot'));
}
insert accounts;
Test.startTest();
Database.executeBatch(new UnratedAccountBatch(), 200);
Test.stopTest();
Assert.areEqual(150, [SELECT COUNT() FROM Account WHERE Rating = 'Cold'],
'All unrated accounts should become Cold');
Assert.areEqual(5, [SELECT COUNT() FROM Account WHERE Rating = 'Hot'],
'Already rated accounts must not change');
}
}The second assertion matters as much as the first. A batch with a broken WHERE clause could rate every account, and a test that checks only the processed records would miss it.
You usually cannot test multi-chunk behavior, such as state kept across execute calls with Database.Stateful. To cover that logic, move it into a plain method that takes a list and returns a result, and call that method directly from a normal unit test.
Testing @future methods
A @future method runs after the calling transaction ends. The start/stop pair forces it to run in the test.
public with sharing class AccountSync {
@future
public static void markSynced(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Synced';
}
update accounts;
}
}
@isTest
private class AccountSyncTest {
@isTest
static void marksAccountsSynced() {
Account acc = new Account(Name = 'Sync me');
insert acc;
Test.startTest();
AccountSync.markSynced(new Set<Id>{ acc.Id });
Test.stopTest();
Account reloaded = [SELECT Description FROM Account WHERE Id = :acc.Id];
Assert.areEqual('Synced', reloaded.Description, 'Future method should update the record');
}
}Future methods accept only primitives and collections of primitives, which is why the code passes Set<Id> and not Set<Account>. Prefer Queueable for new work, since it accepts richer parameters and can be monitored by job Id. You will still meet @future in existing code, and this is how to test it.
Differences at a glance
| Aspect in a test | Queueable | Batch | @future |
|---|---|---|---|
| Start with | `System.enqueueJob` | `Database.executeBatch` | Direct method call |
| Runs when | `Test.stopTest()` | `Test.stopTest()` | `Test.stopTest()` |
| Main restriction | No chaining | One `execute` call only | Primitive parameters only |
| Callouts need | `Database.AllowsCallouts` | `Database.AllowsCallouts` | `@future(callout=true)` |
| Check results by | Re-querying records | Re-querying records | Re-querying records |
Async code that makes callouts
Async classes that call external services follow the same rule as any other test: real callouts are blocked, so register a mock with Test.setMock before Test.startTest(). Declare the class with Database.AllowsCallouts, or use @future(callout=true), or the callout throws in production even if your mock works.
A test inserting records and then enqueuing a callout job in the same transaction can hit the "uncommitted work pending" error, because callouts are not allowed after DML in the same transaction. Putting the enqueue inside the start/stop pair avoids this, since the job runs in its own transaction.
Checking job status
Sometimes the visible result is not a changed record, for example when a job should only run once or should be skipped. You can query AsyncApexJob after Test.stopTest():
AsyncApexJob job = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE ApexClass.Name = 'UnratedAccountBatch'
ORDER BY CreatedDate DESC
LIMIT 1
];
Assert.areEqual('Completed', job.Status, 'Batch should complete');
Assert.areEqual(0, job.NumberOfErrors, 'Batch should have no errors');Use this as a supplement. A completed job proves that nothing threw, but it does not prove that the data is right.
Common mistakes
- Enqueuing outside the start/stop pair. The job may not have run when you assert, so the test fails or passes by accident.
- Asserting on stale variables. Records held in memory do not reflect what the job did. Query again.
- Testing only the happy path. Include records the job should skip, and a case where the job should fail, such as a job that throws on bad input. For a failure inside async code, assert on the side effect you expect, for example that no record was changed.
- Passing more records than the scope. In a batch test this leaves records unprocessed and makes counts wrong.
- Relying on
SeeAllData=trueto find records for the job. Create the data in the test.
Exercise
A test enqueues a Queueable with System.enqueueJob, then immediately queries the records the job should update and asserts on them. The assertion fails even though the job code is correct. What is the most likely cause, and how do you fix it?
Show answer
The enqueue happened outside Test.startTest/Test.stopTest, so the job had not run when the query executed. Move the System.enqueueJob call between Test.startTest() and Test.stopTest(), and run the query and assertions after Test.stopTest().
Exercise
A batch class has a scope of 200, and your test inserts 500 matching records, then asserts that all 500 were updated. Why does this fail, and what should you change?
Show answer
A test runs only one execute call, so at most 200 records are processed and the other 300 are left unchanged. Reduce the test data to 200 records or fewer, or pass a larger scope that still fits governor limits. Move any logic that depends on multiple chunks into a plain method and test it directly.
Exercise
Why does a test for a Queueable that chains another Queueable usually check Test.isRunningTest() in the code under test?
Show answer
Salesforce does not allow chaining Queueable jobs inside a test, so the second System.enqueueJob call would throw. Guarding it with !Test.isRunningTest() lets the first job run to completion in the test. The chained job is then tested separately by enqueuing it directly.