Sub topic 7
Fresh governor limits with Test.startTest and Test.stopTest
This chapter assumes you can write a basic @IsTest method, insert test data with DML, query it with SOQL, and recognize the common governor limits (100 SOQL queries, 150 DML statements per transaction). It builds on the earlier chapters on test data and @TestSetup.
The problem these methods solve
A test method runs as one Apex transaction. Everything it does counts against one set of governor limits. That includes building test data, calling the code under test, and running your assertions.
This causes two problems:
- Setup eats the budget. A test that creates many records, runs several queries to look up profiles or record types, and then calls your code can reach a limit that production code would never reach. The test fails for reasons that have nothing to do with your code.
- Asynchronous work does not run. Queueable jobs,
@futuremethods, batch jobs, and scheduled jobs are normally started in the background. A test method would finish before any of that work ran, so there would be nothing to assert on.
Test.startTest() and Test.stopTest() address both problems. They mark the part of the test that exercises the code under test.
What the pair does
Between the two calls, the following applies:
- Limits reset. The code between the calls gets a fresh set of governor limits. Queries, DML rows, CPU time, and heap are counted from zero.
- Setup is excluded. Whatever you did before
startTestis counted separately. This includes data creation and any@TestSetupwork. - Async work is held. Jobs you enqueue between the calls do not run yet.
- Async work runs at
stopTest. WhenTest.stopTest()executes, all held asynchronous work runs synchronously. The test method waits for it. AfterstopTestreturns, the results are in the database and you can assert on them. - Counters go back. After
stopTest, the limit counters return to the values they had when you calledstartTest.
Seeing the reset
You can observe the reset with the Limits class. Limits.getQueries() returns the number of SOQL queries used so far, and Limits.getLimitQueries() returns the maximum.
@IsTest
private class LimitsResetTest {
@IsTest
static void startTestResetsQueryCount() {
insert new Account(Name = 'Acme');
List<Account> setupRead = [SELECT Id FROM Account];
Integer usedInSetup = Limits.getQueries();
Assert.isTrue(usedInSetup > 0, 'Setup should have used at least one query');
Test.startTest();
Integer usedAtStart = Limits.getQueries();
List<Account> inside = [SELECT Id FROM Account];
Integer usedAfterOneQuery = Limits.getQueries();
Test.stopTest();
Assert.areEqual(0, usedAtStart, 'Query count should be reset by startTest');
Assert.areEqual(1, usedAfterOneQuery, 'Only the query inside the block should count');
Assert.areEqual(1, setupRead.size(), 'Setup read should see the inserted account');
Assert.areEqual(1, inside.size(), 'Query inside the block should see the account');
}
}In real tests you rarely assert on the counters. The example shows what the platform does, so the behavior is not a surprise when a limit error appears in your own tests.
Testing asynchronous code
The most common use of the pair is to run async code. Here is a Queueable job that sets a rating on accounts, and a test that proves it ran.
public class AccountRatingJob implements Queueable {
private List<Id> accountIds;
public AccountRatingJob(List<Id> accountIds) {
this.accountIds = accountIds;
}
public void execute(QueueableContext context) {
List<Account> accts = [SELECT Id, Rating FROM Account WHERE Id IN :accountIds];
for (Account a : accts) {
a.Rating = 'Warm';
}
update accts;
}
}
@IsTest
private class AccountRatingJobTest {
@IsTest
static void jobSetsRatingAfterStopTest() {
Account acct = new Account(Name = 'Acme');
insert acct;
Test.startTest();
System.enqueueJob(new AccountRatingJob(new List<Id>{ acct.Id }));
Account beforeStop = [SELECT Rating FROM Account WHERE Id = :acct.Id];
Test.stopTest();
Account afterStop = [SELECT Rating FROM Account WHERE Id = :acct.Id];
Assert.isNull(beforeStop.Rating, 'Job should not have run before stopTest');
Assert.areEqual('Warm', afterStop.Rating, 'Job should set the rating when stopTest runs');
}
}The test reads the account twice. The read before stopTest shows the job has not run. The read after stopTest shows the result. Always re-query after stopTest. The acct variable in memory is never updated by the job, so asserting on it would check stale data.
The same rule holds for other asynchronous types:
| Async type | Started by | When it runs in a test |
|---|---|---|
| Queueable | `System.enqueueJob` | At `stopTest` |
| Future method | Calling a method marked `@future` | At `stopTest` |
| Batch Apex | `Database.executeBatch` | At `stopTest`, for one `execute` call (see below) |
| Scheduled Apex | `System.schedule` | At `stopTest` |
Edge cases and limits of the approach
- Only one pair per test method. You can call
Test.startTest()once andTest.stopTest()once in a method. CallingstartTesta second time is an error. If you need two separate measured blocks, write two test methods. - Unbalanced calls. Code after
startTestbut before an explicitstopTeststill gets fresh limits. If you never callstopTest, held async work does not run. Always call both. - Batch jobs run one chunk. In a test,
Database.executeBatchprocesses a singleexecuteinvocation. Keep the scope small enough that your test data fits in one chunk, and teststartandfinishlogic by calling the methods directly if you need more. - Chained jobs. Salesforce documents that chaining one Queueable from another inside a test causes an error. Guard the chaining call with
Test.isRunningTest()if your production code chains, and test each job on its own. - Exceptions in async code. If an async job throws an unhandled exception, the failure shows up when
stopTestruns, so the test fails at that line. A failing line number pointing atTest.stopTest()usually means the job failed, notstopTestitself. - Order of data creation matters. Create all records before
startTest. Data created inside the block counts against the fresh limits, which hides how much headroom your code really has.
Using the pair with bulk tests
The reset matters most in bulk tests. Your setup might insert 200 records, which uses DML rows and possibly triggers. The code under test then has to process all 200 within its own limits.
@IsTest
private class BulkResetExampleTest {
@TestSetup
static void setup() {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accts.add(new Account(Name = 'Bulk ' + i, AnnualRevenue = 2000000));
}
insert accts;
}
@IsTest
static void bulkRunStaysWithinLimits() {
List<Account> accts = [SELECT Id, AnnualRevenue, Rating FROM Account];
Test.startTest();
AccountService.flagLargeAccounts(accts);
Integer dmlStatements = Limits.getDmlStatements();
Test.stopTest();
Assert.areEqual(1, dmlStatements, 'Service should use one DML statement for all 200 records');
Integer hot = [SELECT COUNT() FROM Account WHERE Rating = 'Hot'];
Assert.areEqual(200, hot, 'All 200 large accounts should be flagged');
}
}This test uses AccountService from the bulk testing chapter. The assertion on Limits.getDmlStatements() is meaningful here. Because the counter was reset at startTest, the value reflects only what the service did. A service that called update inside a loop would report 200 and the test would fail clearly, long before production traffic did.
Common mistakes
- Asserting before
stopTest. The async work has not run, so the assertion sees old data and fails. - Asserting on in-memory records after async work. Re-query instead.
- Doing setup inside the block. The limit reset then hides setup cost and makes your measurements less accurate.
- Calling
startTesttwice. Split the test into two methods. - Assuming
stopTestresets limits for later code. AfterstopTest, counters return to the pre-start values, so a query-heavy assertion section can still hit the setup limits.
Exercise
A test enqueues a Queueable job between Test.startTest() and Test.stopTest(), and then asserts on the Account variable it inserted earlier, without querying again. The assertion on the updated field fails. Give two reasons the assertion fails and how to fix the test.
Show answer
First, if the assertion sits before Test.stopTest(), the job has not run yet, so nothing has changed. Second, even after stopTest the job updated records in the database, not the in-memory Account variable, so the variable still holds the old value. Fix it by calling Test.stopTest() first and then re-querying the record by Id, for example [SELECT Rating FROM Account WHERE Id = :acct.Id], and asserting on the queried result.
Exercise
Why should test data be created before Test.startTest() rather than inside the block?
Show answer
Work before startTest is counted against a separate set of limits, so setup cost does not consume the fresh limits given to the code under test. Creating data inside the block uses up that fresh budget and makes any limit assertions less accurate. It can also hide the real limit usage of the code you are testing.