Skip to content

Apex test data: @TestSetup methods and test data factories

How to create reliable test records in Apex using @TestSetup and a test data factory, with patterns for bulk tests, lookups and unique fields.

6 minute readUpdated By Kappa Vinay

Apex tests do not see your org’s records by default. Each test has to create the data it needs, which is good for reliability and tedious to write. Two patterns keep that work small: a test data factory, and @TestSetup methods.

A test data factory

A factory is an @IsTest class with static methods that build records. Tests call it instead of repeating new Account(...) everywhere. When a new required field or validation rule appears, you fix one method and every test recovers.

Apex
@IsTest
public class AccountTestDataFactory {
    public static List<Account> createAccounts(Integer count, Boolean doInsert) {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < count; i++) {
            accounts.add(new Account(
                Name = 'Test Account ' + i,
                Industry = 'Technology'
            ));
        }
        if (doInsert) {
            insert accounts;
        }
        return accounts;
    }
}

The doInsert flag matters. Returning records without inserting them lets a test adjust a field first, or test a before insert trigger with exactly the values it needs.

@TestSetup

A method annotated with @TestSetup runs once before the test methods in its class. The records it inserts are available to every test method, and changes made by one test are rolled back before the next one starts.

Apex
@IsTest
private class AccountServiceTest {
    @TestSetup
    static void setupTestData() {
        AccountTestDataFactory.createAccounts(200, true);
    }

    @IsTest
    static void updatesRatings() {
        List<Account> accounts = [SELECT Id FROM Account];
        Test.startTest();
        AccountService.updateRatings(accounts);
        Test.stopTest();
        Assert.areEqual(200, [SELECT COUNT() FROM Account WHERE Rating = 'Hot']);
    }
}

Test methods query the records they need. Static variables set inside the setup method are not carried over to test methods, so do not try to pass records that way.

Habits that prevent flaky tests

  • Test with 200 records at least once. Triggers receive records in batches of up to 200, and bulk problems only show up at that size.
  • Never hard-code record IDs. They differ in every org and sandbox. Create the parent record and use its Id.
  • Make unique fields unique. Add the loop index to names, emails and usernames so duplicate rules and unique constraints do not fire.
  • Wrap the code under test in Test.startTest() and Test.stopTest() to get a fresh set of governor limits and to force asynchronous work to finish.
  • Assert on results, not just on the absence of errors.

Parent and child records

Insert parents first, then build children that reference them. In a factory this usually means a method that accepts the parent records as a parameter.

Apex
List<Account> accounts = AccountTestDataFactory.createAccounts(2, true);
List<Contact> contacts = new List<Contact>();
for (Account acc : accounts) {
    contacts.add(new Contact(LastName = 'Test', AccountId = acc.Id));
}
insert contacts;

Generated test data is a starting point. Your org’s required fields, validation rules, duplicate rules and record types decide what a valid record looks like.