# How do Test.startTest() and Test.stopTest() enforce synchronous execution of asynchronous jobs during unit testing?

**Topic:** Apex · **Difficulty:** Medium · **Tags:** Apex, Asynchronous Apex, Unit Testing

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Arrange test data before `startTest()`.
2. Call `Test.startTest()`.
3. Enqueue the job (`System.enqueueJob`, `Database.executeBatch`, `System.schedule`, or a future call).
4. Call `Test.stopTest()`; the job executes now.
5. 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:**
```apex
@IsTest
static void testQueueable() {
    Account a = new Account(Name = 'Test');
    insert a;

    Test.startTest();
    System.enqueueJob(new SyncAccountsJob(new List<Id>{ a.Id }));
    Test.stopTest(); // job runs here

    Account result = [SELECT Id, Sync_Status__c FROM Account WHERE Id = :a.Id];
    System.assertEquals('Synced', result.Sync_Status__c);
}
```

**Hidden gotchas & must-remember points:**
- `Test.enqueueJob` does not exist; use `System.enqueueJob` inside the block.
- Only one batch `execute()` runs in tests.
- Chaining a queueable from a queueable throws or is skipped in tests; guard with `Test.isRunningTest()`.
- Callout mocks are mandatory.
- Assertions placed before `stopTest()` see no results.
- Only one startTest/stopTest pair is allowed per test method.

**Best practice:** Assert on data outcomes after `stopTest()`, and keep batch tests under one scope of records.

---
Source: ForceChallenges · last updated 2026-11-02
