Sub topic 8
Using Test.startTest and Test.stopTest
This chapter assumes you can write a basic Apex test class with @isTest methods and assertions. It also assumes you know what governor limits are and that Queueable and future methods run asynchronously. Here you will learn what Test.startTest() and Test.stopTest() do, when to use them, and which mistakes make a test pass for the wrong reasons.
What the pair does
Test.startTest() and Test.stopTest() mark the part of a test method that exercises the code under test. They do two separate things.
- Governor limits are reset. Code that runs between the two calls gets a fresh set of limits. Setup code before
startTestuses its own, separate set. WhenstopTestreturns, the counters for the setup code resume where they stopped. - Asynchronous work runs at
stopTest. Future methods, Queueable jobs, Batch Apex and scheduled jobs started between the calls are held back. They run synchronously whenstopTest()is called, so your assertions after it can see their results.
| Moment | Effect |
|---|---|
| Before `Test.startTest()` | Setup code runs under its own limits. |
| Between the calls | The code under test gets fresh limits. Async jobs are queued but do not run. |
| At `Test.stopTest()` | Queued async jobs run to completion, each with its own limits. |
| After `Test.stopTest()` | The test method returns to the setup code's limits. You can query and assert. |
Testing a Queueable job
The most common reason to use the pair is asynchronous code. Without stopTest, a Queueable job never runs inside the test, and your assertions would check data the job has not yet changed.
This example marks accounts as reviewed in a Queueable job.
public with sharing class AccountReviewJob implements Queueable {
private List<Id> accountIds;
public AccountReviewJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accounts = [SELECT Id, Description FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Description = 'Reviewed';
}
update accounts;
}
}
@isTest
private class AccountReviewJobTest {
@isTest
static void marksAccountsAsReviewed() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Review ' + i));
}
insert accounts;
List<Id> ids = new List<Id>(new Map<Id, Account>(accounts).keySet());
Test.startTest();
System.enqueueJob(new AccountReviewJob(ids));
Test.stopTest();
Integer reviewed = [SELECT COUNT() FROM Account WHERE Description = 'Reviewed' AND Id IN :ids];
Assert.areEqual(5, reviewed, 'The job should have reviewed every account');
}
}The insert is outside the block because it is setup, not the behavior under test. The query comes after stopTest() because that is the first point where the job has finished.
If you moved the query above Test.stopTest(), it would return 0. The job would still be waiting in the queue.
Other asynchronous code
The same rule applies to the other async types.
- Future methods: a call to a method marked
@futurebetween the two calls runs atstopTest. - Batch Apex:
Database.executeBatchbetween the calls runs atstopTest. In a test, Salesforce runs a singleexecuteinvocation, so keep the test data within one batch scope (at most 200 records for the default scope). A batch that chains to another batch fromfinishwill not chain in a test. - Scheduled Apex:
System.schedulebetween the calls runs the job atstopTest, regardless of the cron time you give it.
A scheduled job's cron expression is still validated, so use a valid one.
Measuring limits in the code under test
Fresh limits also let you assert how much of a limit the code under test used. The Limits class reports consumption since the last reset. Between the two calls, it reports only what the code under test consumed.
@isTest
private class AccountTriggerLimitsTest {
@isTest
static void bulkInsertUsesOneDmlStatement() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Limit ' + i, AnnualRevenue = 2000000));
}
Test.startTest();
insert accounts;
Integer dmlStatements = Limits.getDmlStatements();
Integer queries = Limits.getQueries();
Test.stopTest();
Assert.areEqual(1, dmlStatements, 'The insert should be a single DML statement');
Assert.areEqual(0, queries, 'The trigger should not run SOQL');
}
}This turns a limit regression into a failing test. If someone later adds a query inside a loop in the trigger, the query count rises with the number of records. The assertion fails even though the test never reaches the actual 100-query limit.
Read Limits values before stopTest(). Once async jobs have run and the context has switched back, the numbers no longer describe only your code.
Rules and gotchas
- One pair per test method. Calling
Test.startTest()twice in the same method throws aSystem.FatalException. If you need two separate measurements, use two test methods. - Keep the block small. Put only the call under test between the two calls. If you put the whole setup inside, the setup consumes the fresh limits and you lose the isolation.
- Fresh limits can hide real problems. In production, your code runs in a transaction that may already have used queries and DML from triggers, flows and other code. A test that passes with a full fresh budget does not prove the code fits when the budget is half used. Use
Limitsassertions and bulk data to catch this. stopTestis required for async results. A test that callsTest.startTest()but forgetsTest.stopTest()fails at the end of the method.- Assertions inside the block are allowed. Only async side effects are unavailable there.
- It is not a callout mock. The pair does not allow real HTTP callouts. A callout still needs
Test.setMock, which you set beforestartTestor inside the block.
When you do not need the pair
For simple synchronous code, such as the DiscountCalculator from earlier, the pair adds nothing. The code under test uses few limits, and no async work needs to be flushed. Many teams still use it for every test that includes DML, to make the "act" step visible to readers. That is a style choice. It is harmless as long as the block stays small.
Use the pair when any of these is true:
- The code under test starts a future, Queueable, Batch or scheduled job.
- The test creates a lot of setup data and you want the code under test measured on its own.
- You want to assert on
Limitsvalues for the code under test.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion shows async changes are missing | Asserted before `Test.stopTest()` | Move the assertion after `stopTest()`. |
| `System.FatalException` about the test already started | Two `Test.startTest()` calls in one method | Split into two test methods. |
| Test passes but production hits limits | Setup inside the block, or reliance on fresh limits | Keep the block small and assert on `Limits`. |
| Batch test only processes part of the data | Test runs a single `execute` | Keep test data within one scope. |
| Job runs with unexpected old data | Data created after `stopTest()` | Create data before the job is enqueued. |
Exercise
A test inserts 10 contacts, then calls Test.startTest(), enqueues a Queueable job that sets a field on those contacts, and queries the contacts to assert the field before calling Test.stopTest(). The assertion fails. Why, and how do you fix it?
Show answer
The Queueable job is held in the queue until Test.stopTest() is called, so the query before it sees the original data. Move the query and assertion after Test.stopTest(). The insert of the 10 contacts can stay before Test.startTest().
Exercise
You add Assert.areEqual(1, Limits.getDmlStatements()) after Test.stopTest() in a test whose code under test is a single insert, and the assertion fails with a different count. What is the likely cause, and where should the Limits call go?
Show answer
After Test.stopTest(), the test is back on the setup code's limits, which already counted the DML used to create test data. The call should go between Test.startTest() and Test.stopTest(), right after the code under test, where the counters cover only that code.