Test.startTest and Test.stopTest
By the end of this lesson, you'll be able to:
- Explain what Test.startTest() and Test.stopTest() do to governor limits
- Use them to separate test-data setup from the code actually being tested
- Recognize their role in testing asynchronous code
Prerequisites: "Creating Test Data"
A fresh set of governor limits for the code under test
@isTest
static void bulkInsertStaysWithinLimits() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Test Account ' + i));
}
Test.startTest();
insert accounts; // governor limits reset here — this DML gets a fresh budget
Test.stopTest();
System.assertEquals(200, [SELECT COUNT() FROM Account]);
}
Everything before Test.startTest() (building 200 Account objects, here) doesn't count toward the governor limits Module 25 covered; everything between startTest() and stopTest() gets its own fresh, separate limit budget — letting a test set up substantial data without that setup competing for the same limits as the actual code being verified.
Why this matters for asynchronous code
Test.startTest();
someService.queueAsyncWork(); // enqueues a Queueable job (a later module covers these)
Test.stopTest();
// by this point, the async job has actually finished running
List<Result__c> results = [SELECT Id FROM Result__c];
System.assertEquals(1, results.size());
Test.stopTest() has a second important effect: any asynchronous Apex enqueued between startTest() and stopTest() is forced to run synchronously, to completion, before stopTest() returns — without this, a test asserting on the async job's results might run before that job had actually finished, in a real (non-test) execution.
Exercise
Wrap this test's DML in Test.startTest()/Test.stopTest(), keeping the data setup loop before the boundary.
Show hint
Test.startTest() goes right before the insert statement.
Test.startTest and Test.stopTest Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Test.startTest() and Test.stopTest() mark the boundary between setting up test data and running the code actually being tested — resetting governor limits at that boundary and forcing async code to finish before assertions run.