Sub topic 5
Async jobs run synchronously at stopTest
This chapter assumes you can write an @IsTest class with assertions and DML, and that you know what @future, Queueable, Batch and Schedulable Apex do. It explains how Test.stopTest() turns asynchronous work into something a test can check.
The problem: the job runs in another transaction
In production, a call such as System.enqueueJob(...) returns right away. The platform runs the job later, in its own transaction, on its own schedule. Your calling code never waits for it.
A test can't live with that. Assertions run in the same transaction as the code that queues the job. If the job hasn't run, the data hasn't changed, and the assertion fails or checks stale state. Waiting or polling isn't an option either, because the test transaction ends before the platform picks up the job.
Apex solves this with Test.startTest() and Test.stopTest(). Any async work queued between the two calls runs synchronously when stopTest() is called, and stopTest() doesn't return until it finishes. The next line of your test then sees the finished result.
What happens at each step
The sequence is the same for every async type.
Three details matter here:
- The job does not start when you queue it. It starts when
stopTest()is called. stopTest()blocks until the job finishes. It does not return a result. You find out what happened by reading the database.- The job runs in its own context, with its own set of governor limits. The limits are the async ones, which are higher for some resources than the synchronous ones.
Seeing the timing for yourself
The following test prints nothing and mocks nothing. It only checks the record at three points, so you can see when the change appears.
public class AccountTagger {
@future
public static void tag(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Tagged';
}
update accounts;
}
}
@IsTest
private class AccountTaggerTest {
@IsTest
static void changeAppearsOnlyAfterStopTest() {
Account a = new Account(Name = 'Timing Test');
insert a;
Test.startTest();
AccountTagger.tag(new Set<Id>{ a.Id });
Account beforeStop = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.isNull(beforeStop.Description, 'Future method has not run yet');
Test.stopTest();
Account afterStop = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Tagged', afterStop.Description);
}
}The first query sits inside the window, so it still sees the original value. The second query sits after stopTest() and sees the change. The assertion between the calls is only there to demonstrate the timing. In a real test you would normally assert after stopTest().
Both queries create a fresh Account instance on purpose. A variable you queried earlier holds a snapshot and never updates itself.
What runs for each async type
All four types follow the same rule, but each has its own details.
| Async type | What runs at stopTest | Detail to remember |
|---|---|---|
| `@future` method | The method body runs once for each call queued in the window | Pass IDs, not records, as you would in production |
| Queueable | The `execute` method of each job enqueued in the window | A job that enqueues a child job hits a test-context limit (see below) |
| Batch Apex | `start`, one `execute` call, then `finish` | One `execute` only, so keep the test data within one scope (up to 200 records) |
| Schedulable | Nothing, if the cron time is in the future | Check the `CronTrigger` record, or call `execute` directly to test the logic |
The following chapters cover each type in detail. For now, take away that the entry point is the same for all of them: queue the work inside the window, call stopTest(), then check the data.
Work outside the window is not covered
Only work queued between startTest() and stopTest() is run for you. Code that queues a job before startTest() gives you no guarantee that it will finish before your assertions. The same applies to jobs created by a trigger during your setup DML.
This is why test data setup belongs before the window and the code under test belongs inside it. If your setup insert fires a trigger that enqueues a job, that job competes with your own. To keep the test predictable, call startTest() immediately before the code you are testing, not at the top of the method.
@IsTest
private class WindowPlacementTest {
@IsTest
static void onlyTheCodeUnderTestIsInsideTheWindow() {
// Setup: outside the window
Account a = new Account(Name = 'Placement Test');
insert a;
// Code under test: inside the window
Test.startTest();
AccountTagger.tag(new Set<Id>{ a.Id });
Test.stopTest();
// Assertions: after the window
Assert.areEqual(
'Tagged',
[SELECT Description FROM Account WHERE Id = :a.Id].Description
);
}
}Multiple jobs in one window
You can queue several jobs in one window. All of them run at stopTest().
@IsTest
private class MultipleFutureCallsTest {
@IsTest
static void everyQueuedCallRuns() {
List<Account> accounts = new List<Account>{
new Account(Name = 'First'),
new Account(Name = 'Second')
};
insert accounts;
Test.startTest();
for (Account a : accounts) {
AccountTagger.tag(new Set<Id>{ a.Id });
}
Test.stopTest();
Integer tagged = [SELECT COUNT() FROM Account WHERE Description = 'Tagged'];
Assert.areEqual(2, tagged);
}
}The loop queues two future calls. In production this pattern would be wasteful, because one call with a set of IDs does the same work. The test shows only that both calls are executed. The number of async calls you can queue in a single transaction is still limited, so the limit applies inside the window too.
Exceptions inside the job
If the async code throws an unhandled exception, it happens during stopTest(), and the test reports a failure at that line. A failing stopTest() usually means the job itself has a bug, not the test framework. Look at the stack trace for the job class.
If your job catches its own exceptions and writes to a log object or sets an error field, the test continues normally. In that case, assert on the error record to confirm the failure path works.
Other effects of the window
Calling startTest() also gives the code inside the window a fresh set of governor limits, separate from the limits used by your setup. The next chapter on limits covers that. Two related rules are worth knowing now:
- A test method can call
startTest()andstopTest()only once. A second call tostartTest()throws an exception, so you can't run two separate async phases in one method. Use a second test method instead. - If you never call
stopTest(), the queued async work does not run during the test, and the platform discards it when the test finishes. This is the most common cause of a test that passes the code but fails the assertion.
Common mistakes
- Asserting before
stopTest(). The job hasn't run, so the data is unchanged. Move the assertion after the call. - Reusing a queried record. After
stopTest(), query the record again. The old variable still holds the original values. - Queuing the job before
startTest(). The job isn't guaranteed to run atstopTest(). Move the call inside the window. - Leaving out the mock. A real callout in an async job fails in a test. Call
Test.setMockbeforestopTest(), because the job runs at that point. - Expecting more than one batch
execute. The test runs one. Keep the data within one scope.
Check your understanding
Exercise
A test inserts an Account, calls Test.startTest(), enqueues a Queueable job that sets the Account's Description, then asserts on the Description before calling Test.stopTest(). The assertion fails. Why, and what is the fix?
Show answer
The Queueable job does not run when it is enqueued. It runs synchronously when Test.stopTest() is called, so before that line the Description still has its original value. Move the assertion after Test.stopTest() and re-query the Account, because the earlier variable holds a snapshot of the old data.
Exercise
Your test calls Test.startTest() and Test.stopTest() around a future call, then calls Test.startTest() again to test a second future call in the same method. What happens, and how do you restructure it?
Show answer
The second startTest() call throws an exception, because a test method allows only one startTest/stopTest pair. Split the scenarios into two test methods, each with its own window, or queue both calls inside a single window if they can run together.