Intermediate 15 min read

Setting Up Test Data

By the end of this lesson, you'll be able to:

  • Use @testSetup to create shared test data once per test class
  • Use Test.startTest() and Test.stopTest() to reset governor limits and isolate async behavior

Prerequisites: Anatomy of a Test Class

@testSetup: shared data, once

A method annotated @testSetup runs once before each test method in the class. Because every test method runs in its own rolled-back transaction, each one sees its own fresh copy of whatever @testSetup inserted — no leftover data leaking between tests, and no repeated setup boilerplate in every method.

Test.startTest() and Test.stopTest()

Code before Test.startTest() shares governor limits with the arrange/setup phase. Code between startTest() and stopTest() gets a fresh set of limits, isolating the code actually under test. stopTest() also forces any @future, Queueable, or Batch Apex enqueued inside the block to run synchronously before continuing — essential for asserting on async side effects.

Shared setup data with a bracketed test

@isTest
private class OpportunityServiceTest {
    @testSetup
    static void makeData() {
        insert new Account(Name = 'Acme Corp');
    }

    @isTest
    static void closingAnOpportunityUpdatesTheAccount() {
        Account acc = [SELECT Id FROM Account LIMIT 1];

        Test.startTest();
        OpportunityService.closeAllFor(acc.Id);
        Test.stopTest();

        // assertions here see the results of any async work above
    }
}

@testSetup's Account is available fresh to every test method in the class; Test.startTest()/stopTest() brackets just the code being tested, and guarantees any async work inside it has finished by the time stopTest() returns.

Exercise

Write an @testSetup method that inserts a Contact with LastName 'Doe', and a test method that queries for it and asserts it exists.

Show hint

@testSetup methods must be static and return void.

APEX

Setting Up Test Data — Quick Check

1. How often does an @testSetup method run per test method in the class?

2. Test.stopTest() forces any Queueable or @future work enqueued inside the Test.startTest()/stopTest() block to run before it returns.

3. Why bracket the code under test with Test.startTest() and Test.stopTest()?

Log in to submit the quiz and save your score.

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

@testSetup creates data once, with every test method getting its own fresh copy, avoiding duplicated setup code; Test.startTest()/stopTest() resets governor limits for the code under test and forces any enqueued async work to run before stopTest() returns.