Sub topic 4
Fresh governor limits between startTest and stopTest
This chapter assumes you can write a basic @IsTest class, use SOQL and DML, and know the common governor limits (SOQL queries, DML statements, heap, CPU time). It also assumes you know roughly what future, Queueable, Batch and Schedulable Apex do.
Why limits matter in tests
Every Apex transaction has governor limits. A test method is one transaction, and everything it does counts against one set of limits: creating test data, calling the code under test, and querying results.
That causes a problem. Suppose a test inserts a lot of records to set up a scenario, and the code under test then needs most of the SOQL and DML budget. The test could fail with a limit exception even though the code is fine in production, where it would run in a fresh transaction.
Test.startTest() and Test.stopTest() fix this. The code between them gets its own, fresh set of limits.
The three limit contexts
A test method that uses the test window works with three separate limit contexts:
- Before startTest. Test data setup runs here. It uses the test method's original limits.
- Between startTest and stopTest. The code under test runs here with a fresh set of limits, as if it were a new transaction.
- After stopTest. Assertions run here. The test goes back to the original limits from context 1, including whatever setup already consumed.
Async work queued inside the window runs when Test.stopTest() is called. It gets its own limits, and these are the asynchronous limits (higher for some resources, as the table below shows).
Synchronous and asynchronous limits
Some limits are higher when code runs asynchronously. The ones you meet most often:
| Limit | Synchronous | Asynchronous |
|---|---|---|
| SOQL queries per transaction | 100 | 200 |
| Total heap size | 6 MB | 12 MB |
| CPU time | 10,000 ms | 60,000 ms |
| DML statements | 150 | 150 |
| DML rows | 10,000 | 10,000 |
Check the current Apex Developer Guide for the full list, because limits change between releases.
When the test calls an async method inside the window, the method itself returns right away, because it only queues work. The queued job later runs at stopTest and uses the asynchronous column. This means a test can exercise both kinds of limits in a single method: the synchronous code in the window uses fresh synchronous limits, and the job uses its own asynchronous limits.
Seeing the reset with the Limits class
The Limits class reports how much of each limit the current context has used. You can use it to see the reset directly.
@IsTest
private class LimitsResetTest {
@IsTest
static void startTestResetsQueryCount() {
Account a = new Account(Name = 'Limits Test');
insert a;
// Use up part of the original query budget during setup.
for (Integer i = 0; i < 20; i++) {
List<Account> rows = [SELECT Id FROM Account WHERE Id = :a.Id];
}
Integer usedBefore = Limits.getQueries();
Test.startTest();
Integer usedInWindow = Limits.getQueries();
[SELECT Id FROM Account WHERE Id = :a.Id];
Integer usedAfterOneQuery = Limits.getQueries();
Test.stopTest();
Assert.isTrue(usedBefore >= 20, 'Setup should have used at least 20 queries');
Assert.isTrue(usedInWindow < usedBefore, 'startTest should reset the count');
Assert.areEqual(usedInWindow + 1, usedAfterOneQuery);
}
}The test compares counts instead of hard-coding exact numbers. Exact values can vary with triggers and flows that fire during setup, but the relationship (setup used a lot, the window starts lower) holds.
A practical example: a bulk test
Fresh limits are what let you test a bulk scenario. Take the future method from the earlier chapters:
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;
}
}A bulk test creates 200 accounts in the setup section, then runs the future method with all of them:
@IsTest
private class AccountServiceBulkTest {
@IsTest
static void markReviewedHandles200Accounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
insert accounts;
Set<Id> ids = new Map<Id, Account>(accounts).keySet();
Test.startTest();
AccountService.markReviewed(ids);
Test.stopTest();
Integer reviewed = [SELECT COUNT() FROM Account WHERE Description = 'Reviewed'];
Assert.areEqual(200, reviewed);
}
}The insert of 200 records happens before startTest, so it does not eat into the budget for the code under test. The future method runs at stopTest with its own limits, and the final COUNT() query runs back under the original limits.
What to put inside the window
The window is for the code under test and nothing else. A good rule:
- Put data creation before
Test.startTest(). - Put the call you are testing between
startTestandstopTest. - Put assertions and verification queries after
Test.stopTest().
If you create test data inside the window, that work uses up the fresh limits that are meant to represent production conditions. The test can then pass or fail for reasons that have nothing to do with the code under test. It also makes limit measurements wrong. For example, a Limits.getDmlStatements() reading taken at the end of the window would include your setup DML.
Measuring the code under test
Because the window starts with a clean count, you can check how much of the budget your code uses. This is a useful guard against a change that makes a method query inside a loop.
@IsTest
private class QueryBudgetTest {
@IsTest
static void markReviewedUsesFewQueries() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 50; i++) {
accounts.add(new Account(Name = 'Budget ' + i));
}
insert accounts;
Set<Id> ids = new Map<Id, Account>(accounts).keySet();
Test.startTest();
AccountService.markReviewed(ids);
Integer queriesQueued = Limits.getQueries();
Test.stopTest();
Assert.areEqual(0, queriesQueued, 'Queuing the future call should not run queries');
}
}Reading Limits between the call and stopTest tells you what the synchronous part of your code used. The async part runs at stopTest in a separate context, so its usage does not show up in this count. To check what the async code used, you would put the Limits calls inside the async class itself and, for example, store the values in a record that the test then queries.
Edge cases and pitfalls
- One pair per method. A test method can call
Test.startTest()once. Calling it a second time in the same method throws an exception. If you need several fresh-limit scenarios, write several test methods. - Missing stopTest. If you call
startTestand never reachstopTest, queued async jobs do not run, and your assertions see unchanged data. - Limits come back after stopTest. Code after
stopTestruns against the original limits again. A test that did heavy setup can hit a limit in its final verification queries. Keep setup lean, or use@TestSetupfor shared data, which does not count toward each test method's limits. - The reset does not hide a real bug. Fresh limits mean the window behaves like a new transaction. If the code under test fails inside the window, it would fail in production too, so a limit exception there is a real finding.
- Async limits are not unlimited. The higher async limits apply to the job at
stopTest, but the number of jobs you can queue in one transaction is still capped. For example, a single transaction can queue at most 50 future calls.
Summary of the rules
- Create data before
startTest. It uses the original limits. - Call the code under test inside the window. It gets fresh synchronous limits.
- Async jobs queued in the window run at
stopTestwith their own asynchronous limits. - After
stopTest, you are back on the original limits. Run your assertions there. - Use one
startTest/stopTestpair per test method.
Exercise
A test method inserts 150 records, then calls Test.startTest(), runs a method that performs 90 SOQL queries, calls Test.stopTest(), and then runs 20 more verification queries. The setup used 15 queries. Does the test hit the synchronous limit of 100 queries, and why or why not?
Show answer
No. The 15 setup queries count against the original limits. The 90 queries in the window run against a fresh set of 100, so they fit. After stopTest the test returns to the original limits, which have used only 15, so the 20 verification queries bring the total to 35 in that context. Neither context goes over 100.
Exercise
Why is it a mistake to create the test accounts after Test.startTest() instead of before it?
Show answer
The setup DML and queries would use up the fresh limits that are meant to represent the code under test. That can cause false limit failures, and it makes Limits readings taken in the window include work that is not part of the code being tested.