How do Test.startTest() and Test.stopTest() enforce synchronous execution of asynchronous jobs during unit testing?
Answer
Basics: Async jobs normally run later, which makes them untestable. Test.stopTest() forces all async work started inside the block to complete before the next line, and startTest() also gives the code under test a fresh set of governor limits.
How it works:
- Arrange test data before
startTest(). - Call
Test.startTest(). - Enqueue the job (
System.enqueueJob,Database.executeBatch,System.schedule, or a future call). - Call
Test.stopTest(); the job executes now. - Query and assert.
Advanced / deep dive: Details that trip people: a batch in a test runs only one execute() invocation, so keep test data at or below the scope size; chained queueables do not run beyond the first level in tests (guard the enqueue of child jobs with !Test.isRunningTest()); callouts need Test.setMock; scheduled jobs run once at stopTest() regardless of cron time. Async jobs started before startTest() run at the end of the test method's transaction or when you stop, not within your limit window. For @future and queueable code, assertions must come after stopTest(). Use System.runAs for setup-object DML (mixed DML) in tests. Query AsyncApexJob to verify status when needed.
Code / config example:
@IsTest
static void testQueueable {
(Name = );
insert a;
Test.startTest();
System.enqueueJob( ( <Id>{ a.Id }));
Test.stopTest();
[SELECT Id, Sync_Status__c FROM Account :a.Id];
System.assertEquals(, result.Sync_Status__c);
}