Sub topic 8
Using Test.startTest and Test.stopTest
This chapter assumes you can write a basic test class with @isTest methods and that you know the common governor limits, such as 100 SOQL queries and 150 DML statements per transaction. It covers what Test.startTest and Test.stopTest do and how to place them in a test method.
What the pair does
A test method often does a lot of work before it reaches the code under test. It might insert dozens of records or build related data. That setup work uses governor limits. Without a boundary, the setup could use up limits that the code under test needs, and the test could fail for the wrong reason.
Test.startTest() and Test.stopTest() mark the code under test. They have two effects:
- Fresh limits. Code between the two calls gets its own full set of governor limits. Setup before
startTestis counted separately. - Asynchronous work runs. When
stopTestis called, queued@futuremethods, Queueable jobs, and Batch Apex jobs run synchronously. AfterstopTestreturns, you can assert on their results.
Example: testing a future method
A @future method does not run right away in normal Apex. In a test, it waits until stopTest. Here is a small service that uses one.
public with sharing class AccountRatingService {
@future
public static void markHot(Set<Id> accountIds) {
List<Account> accounts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accounts) {
a.Rating = 'Hot';
}
update accounts;
}
}The test inserts the data first, then wraps only the call under test.
@isTest
private class AccountRatingServiceTest {
@isTest
static void futureMethodRunsAtStopTest() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Acme ' + i));
}
insert accounts;
Map<Id, Account> byId = new Map<Id, Account>(accounts);
Test.startTest();
AccountRatingService.markHot(byId.keySet());
Test.stopTest();
Integer hotCount = [SELECT COUNT() FROM Account WHERE Rating = 'Hot' AND Id IN :byId.keySet()];
Assert.areEqual(5, hotCount, 'All five accounts should be rated Hot after the future job runs');
}
}If you ran the query before Test.stopTest(), the count would be 0, because the future job has not run yet. The assertions belong after stopTest.
Rules and common errors
- One pair per test method. Calling
Test.startTesttwice in the same method throws a runtime error. Split the scenario into two test methods instead. - Put only the code under test inside the pair. Data creation inside the block uses the fresh limits. It hides limit problems that would show up in real use, and the test can pass when the real code would fail.
- Assert after
stopTest. Results from async code do not exist before it. - Set mocks first. Call
Test.setMockbefore the code that makes the callout. Putting it beforestartTestis fine. - Each async job is limited. A job started inside the pair gets its own limits when it runs. Chained Queueable jobs do not run inside tests. Only the first job executes.
Quick reference
| Call | Effect |
|---|---|
| `Test.startTest()` | Starts a fresh set of governor limits for the code that follows. |
| `Test.stopTest()` | Ends the block and runs queued async jobs synchronously. |
| `Limits.getQueries()` | Reports the SOQL queries used so far in the current context. |
Exercise
A test inserts 150 records, then calls a Queueable job, and then asserts on the data the job changed. The assertion fails because nothing has changed. Where should Test.startTest and Test.stopTest go, and where should the assertion be?
Show answer
Insert the 150 records before Test.startTest(). Enqueue the job between Test.startTest() and Test.stopTest(). Put the assertion after Test.stopTest(), because the Queueable job runs when stopTest is called. An assertion placed before that point sees the unchanged data.