Sub topic 7
Fresh governor limits with Test.startTest and Test.stopTest
This chapter assumes you can write a basic Apex test class with @IsTest methods and @TestSetup. It also assumes you know what governor limits are and how SOQL and DML work.
Why the pair exists
Every Apex transaction has governor limits, such as 100 SOQL queries and 150 DML statements in synchronous code. A test method is one transaction. If the method creates its own data and then calls the code under test, both share the same limit counters. A test can then fail because of its own setup work, not because of the code you are testing.
Test.startTest() and Test.stopTest() mark the section of the test that runs the code under test. Everything between them gets a fresh set of governor limits. Work before Test.startTest() keeps its own counters.
What the pair does
- Resets governor limit counters when
Test.startTest()runs, so setup work does not count against the code under test. - Runs asynchronous work that was queued between the two calls when
Test.stopTest()runs. This covers future methods, Queueable jobs, and Batch Apex. The test waits for that work to finish. - Lets you assert on the results of asynchronous work after
Test.stopTest().
A worked example
The service below queues a Queueable job that marks accounts as reviewed. The test builds its data, starts the measured section, enqueues the job, and stops the measured section. Only then does it query and assert.
public class ReviewJob implements Queueable {
private List<Id> accountIds;
public ReviewJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accts = [SELECT Id FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Description = 'Reviewed';
}
update accts;
}
}
@IsTest
private class ReviewJobTest {
@IsTest
static void jobMarksAccountsAsReviewed() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 10; i++) {
accts.add(new Account(Name = 'Review Test ' + i));
}
insert accts;
List<Id> ids = new List<Id>(new Map<Id, Account>(accts).keySet());
Test.startTest();
System.enqueueJob(new ReviewJob(ids));
Test.stopTest();
Integer reviewed = [SELECT COUNT() FROM Account WHERE Description = 'Reviewed'];
Assert.areEqual(10, reviewed, 'The queued job should have reviewed all 10 accounts');
}
}The insert accts statement runs before Test.startTest(), so it does not use the limits that the job gets. At Test.stopTest(), the job runs synchronously within the test. The query after it sees the updated records.
Common errors
- Asserting before
Test.stopTest(). The queued job has not run yet, so the query returns the old data and the assertion fails. Put assertions on asynchronous results afterTest.stopTest(). - Calling the pair more than once. Each test method can call
Test.startTest()andTest.stopTest()only once. A second call causes a runtime error. - Putting setup inside the pair. Data creation inside the pair uses the fresh limits and hides how close the code under test is to a limit. Create data before
Test.startTest(). - Expecting a reset for everything. Only the counters reset. The data you inserted before the call stays in the database for the rest of the test.
Measuring usage
The Limits class reports how much of a limit a section has used. Inside the pair, you can read it to confirm the code stays within a budget.
@IsTest
private class LimitsExampleTest {
@IsTest
static void serviceUsesFewQueries() {
Account acct = new Account(Name = 'Limits Test');
insert acct;
Test.startTest();
List<Account> found = [SELECT Id FROM Account WHERE Id = :acct.Id];
Integer queriesUsed = Limits.getQueries();
Test.stopTest();
Assert.areEqual(1, found.size(), 'The account should be found');
Assert.areEqual(1, queriesUsed, 'Only one query should run inside the measured section');
}
}Because the counters reset at Test.startTest(), Limits.getQueries() returns 1 here. Without the reset it would also count queries made earlier in the method.
Exercise
A test inserts 50 accounts, calls a method that enqueues a Queueable job, and then asserts on the job's changes. The assertion fails because the changes are missing. The test calls Test.startTest() before the enqueue but never calls Test.stopTest(). What is the fix, and why does it work?
Show answer
Call Test.stopTest() after enqueueing the job and before the assertion. Test.stopTest() makes the queued job run to completion within the test, so the query after it sees the job's changes.
Exercise
A test creates its 200 test records inside the Test.startTest() and Test.stopTest() section, then calls the service. Why is this a poor placement, and where should the creation go?
Show answer
The record creation uses the fresh limits that are meant for the code under test, so the test hides how many limits the service itself uses. Move the creation before Test.startTest(), or into a @TestSetup method.