Sub topic 3
How Test.startTest and Test.stopTest work
This chapter explains what the two methods do, where each part of a test belongs, and which rules apply to them. It assumes you can write a basic @IsTest class, use SObject DML, and know what governor limits are. It also assumes you have a general idea of what @future, Queueable, Batch and Schedulable Apex do.
The problem the test window solves
Asynchronous Apex runs in its own transaction, after the transaction that queued it has finished. A test method is a single transaction. If you call an @future method and then query the record it should change, the future method has not run yet, so your assertion sees the old data and fails.
Test.startTest() and Test.stopTest() solve this. Together they mark a test window. The window does two things:
- Code inside it gets a fresh set of governor limits.
- Async work queued inside it runs synchronously when
Test.stopTest()is called.
After stopTest() returns, the async work is finished and you can assert on its results.
The three zones of a test method
Every test that involves async code has three zones.
| Zone | Position | What belongs here | Limits used |
|---|---|---|---|
| Setup | Before `startTest` | Creating records, custom settings, users | The test's own limits |
| Test window | Between `startTest` and `stopTest` | Only the code under test | A fresh set of limits |
| Verification | After `stopTest` | Re-querying records and asserting | Back to the test's own limits |
A complete example
This example repeats the future method pattern from the topic plan. The comments mark each zone.
public class AccountService {
@future
public static void markReviewed(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}
@IsTest
private class AccountServiceTest {
@IsTest
static void markReviewedUpdatesDescription() {
// Zone 1: setup
Account a = new Account(Name = 'Test Account');
insert a;
// Zone 2: test window
Test.startTest();
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.stopTest();
// Zone 3: verification
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areEqual('Reviewed', result.Description);
}
}The future method does not run when markReviewed is called. It runs when Test.stopTest() is reached. The query after stopTest() returns the updated record.
Why setup goes before startTest
Put data creation before startTest() for two reasons.
First, the setup DML counts against the test's limits, not the window's limits. If you create 150 records in setup and then run code under test that does its own DML, the code under test still starts with a clean DML budget.
Second, the window should hold only the code you want to measure. Keeping setup out of it means a limit failure points at the code under test and not at your test scaffolding.
What the fresh limits mean
When startTest() is called, the governor limit counters reset for the code that follows. When stopTest() is called, the counters return to the values they had before startTest(). This gives the code under test its own full allowance, as it would have in a real transaction.
This has a practical effect. A test that inserts 100 records in setup and then calls code that runs 90 queries does not add the two together. The setup uses its limits, and the window uses a separate set.
The reset applies to the code between the two calls. The async job that runs at stopTest() also gets its own limits, as it would in production, because it is a separate transaction.
One pair per test method
A test method can call Test.startTest() once and Test.stopTest() once. A second call to startTest() in the same method throws a System.FinalException. If you need two separate windows, use two test methods.
@IsTest
private class WindowRuleTest {
@IsTest
static void secondStartTestFails() {
Test.startTest();
try {
Test.startTest();
Assert.fail('Expected a FinalException');
} catch (System.FinalException e) {
Assert.isNotNull(e.getMessage());
}
Test.stopTest();
}
}The same rule explains a common design choice. Keep one behavior per test method, with its own setup and its own window.
What stopTest actually does
When stopTest() runs, three things happen in order:
- The platform runs all async work queued since
startTest(). This covers future methods, Queueable jobs, Batch Apex and scheduled jobs queued within the window. - Each job runs to completion, and a failure in a job is raised in the test.
- The limit counters return to those of the code before
startTest().
The job's DML is committed within the test transaction, so your later queries see it. Everything is still rolled back when the test ends, as with any test data.
Calls that are not in the window
Async work queued outside the window does not run at stopTest(). If you call AccountService.markReviewed(...) in the setup zone, the future method is queued but not forced to run. Queued work stays pending until the test ends, and your assertions will not see its effect.
@IsTest
private class WrongPlacementTest {
@IsTest
static void futureCalledBeforeWindow() {
Account a = new Account(Name = 'Misplaced');
insert a;
// Wrong: the call is outside the window
AccountService.markReviewed(new Set<Id>{ a.Id });
Test.startTest();
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Id = :a.Id];
Assert.areNotEqual('Reviewed', result.Description);
}
}The test passes only because it asserts that the work did not run. In a real test, you would move the call between the two methods.
Test code that has no async work
You can use the window for synchronous code too. The fresh limits are the only benefit then, which is useful for isolating the limit use of the code under test from your setup. If the code queues nothing, stopTest() has no jobs to run and simply restores the counters.
Common mistakes
- Asserting before
stopTest(). The job has not run, so the data is unchanged. Move assertions after the call. - Using stale variables. An object you inserted before the window still holds its old field values. Re-query it after
stopTest(). - Putting setup inside the window. This spends the window's limits and can hide a limit problem in the real code.
- Calling
startTest()twice. This throws aSystem.FinalException. Split the test into two methods. - Queueing async work before
startTest(). It does not run atstopTest().
Summary
Test.startTest()resets governor limits for the code under test.Test.stopTest()runs queued async work synchronously and restores the earlier limit counters.- Setup goes before the window, the code under test goes inside it, and assertions go after it.
- Each test method gets one pair of calls.
- Assert on re-queried records, not on in-memory objects.
Exercise
A test inserts an Account, calls a @future method that sets its Description, and then asserts on the Description, all before calling Test.startTest(). Why does the assertion fail, and how do you fix the test?
Show answer
The future method is queued but not run, because it was called outside the test window and nothing forces it to execute. Move the call to the future method between Test.startTest() and Test.stopTest(), then re-query the Account after Test.stopTest() and assert on the re-queried record.
Exercise
A test method needs to check the effect of two separate async calls, each in its own window. What happens if you call Test.startTest() twice in the same method, and what should you do instead?
Show answer
The second call to Test.startTest() throws a System.FinalException, because a test method may use only one startTest and stopTest pair. Split the test into two test methods, each with its own setup, window and assertions.