is live. Lifetime & Yearly plans on offer. thankful for you ๐Ÿงก

Get the Black Friday deal

Apex

Apex Test Data Factory: A Reusable Pattern for Test Classes

How to build a test data factory in Salesforce: Apex code for Accounts, Contacts and Opportunities, field overrides, @TestSetup and bulk tests.

By Teja, ex-Salesforce engineer ยท Updated November 24, 2026 ยท 8 min read

Apex

A test data factory in Salesforce is an @isTest helper class with static methods that create test records (Accounts, Contacts, Opportunities and so on) in one place. Test classes call these methods instead of building records inline, so each test stays short and every test uses the same valid data. When a validation rule or required field changes, you fix one method instead of forty test classes.

Below: a full example class, a test that calls it, the annotations involved, why tests must not rely on org data, and how to use the factory for bulk trigger tests.

Why test classes need a factory

Without a factory, test classes tend to look like this:

Account acc = new Account(Name = 'Test');
insert acc;
Contact con = new Contact(LastName = 'Smith', AccountId = acc.Id);
insert con;
Opportunity opp = new Opportunity(
    Name = 'Test Opp', StageName = 'Prospecting',
    CloseDate = Date.today(), AccountId = acc.Id
);
insert opp;

That block gets copied into every test class in the org. Then an admin adds a validation rule requiring Industry on Account, and dozens of tests fail on deployment with FIELD_CUSTOM_VALIDATION_EXCEPTION. Somebody now has to edit every copy.

A factory fixes three problems:

  1. One place to change. New required fields, validation rules or record types get handled in a single method.
  2. Consistent data. Every test starts from records that pass the org's rules, so a failing test points at the code under test and not at bad setup data.
  3. Shorter tests. The test method shows only what matters for that scenario: the field values it overrides and the assertions it makes.

A complete TestDataFactory class

The class below creates Accounts, Contacts and Opportunities. Each method takes a record count, an optional map of field overrides, and a flag that controls whether the records are inserted.

@isTest
public class TestDataFactory {

    private static Integer counter = 0;

    private static Integer nextNumber() {
        counter++;
        return counter;
    }

    private static void applyOverrides(SObject record, Map<SObjectField, Object> overrides) {
        if (overrides == null) {
            return;
        }
        for (SObjectField field : overrides.keySet()) {
            record.put(field, overrides.get(field));
        }
    }

    // ---------- Accounts ----------
    public static List<Account> createAccounts(
        Integer count, Map<SObjectField, Object> overrides, Boolean doInsert
    ) {
        List<Account> accounts = new List<Account>();
        for (Integer i = 0; i < count; i++) {
            Account acc = new Account(
                Name = 'Test Account ' + nextNumber()
            );
            applyOverrides(acc, overrides);
            accounts.add(acc);
        }
        if (doInsert) {
            insert accounts;
        }
        return accounts;
    }

    public static Account createAccount() {
        return createAccounts(1, null, true)[0];
    }

    // ---------- Contacts ----------
    public static List<Contact> createContacts(
        Id accountId, Integer count, Map<SObjectField, Object> overrides, Boolean doInsert
    ) {
        List<Contact> contacts = new List<Contact>();
        for (Integer i = 0; i < count; i++) {
            Integer n = nextNumber();
            Contact con = new Contact(
                FirstName = 'Test',
                LastName  = 'Contact ' + n,
                Email     = 'test.contact' + n + '@example.com',
                AccountId = accountId
            );
            applyOverrides(con, overrides);
            contacts.add(con);
        }
        if (doInsert) {
            insert contacts;
        }
        return contacts;
    }

    // ---------- Opportunities ----------
    public static List<Opportunity> createOpportunities(
        Id accountId, Integer count, Map<SObjectField, Object> overrides, Boolean doInsert
    ) {
        List<Opportunity> opps = new List<Opportunity>();
        for (Integer i = 0; i < count; i++) {
            Opportunity opp = new Opportunity(
                Name      = 'Test Opportunity ' + nextNumber(),
                StageName = 'Prospecting',
                CloseDate = Date.today().addDays(30),
                Amount    = 10000,
                AccountId = accountId
            );
            applyOverrides(opp, overrides);
            opps.add(opp);
        }
        if (doInsert) {
            insert opps;
        }
        return opps;
    }
}

Design choices in this class

Map<SObjectField, Object> for overrides. Using Opportunity.Amount as the key instead of the string 'Amount' means the compiler checks the field name. A typo fails at save time, not halfway through a deployment. If you need dynamic field names (for example, from custom metadata), a Map<String, Object> works the same way with record.put(String, Object).

Defaults satisfy required fields only. Account needs Name. Contact needs LastName. Opportunity needs Name, StageName and CloseDate. Add whatever your own org's validation rules require, and nothing more. Extra defaults hide which fields a test depends on.

A counter for unique values. Duplicate rules and unique fields (an external ID, or Email if you've enforced uniqueness) will reject records with identical values. The static counter keeps names and emails distinct within a transaction.

The doInsert flag. Some tests need records already in the database. Others need unsaved records so the test can insert them inside Test.startTest() and measure the trigger. Returning the list either way covers both cases.

Bulk-first signatures. Every method creates a list and does one DML statement. The single-record helper (createAccount()) just wraps the bulk version. This keeps the factory from hitting DML limits when a test asks for 200 records.

Calling the factory from a test class

Assume an Opportunity trigger that sets NextStep to 'Executive review' when Amount exceeds 100,000. Here is a test that uses the factory, @TestSetup, and a 200-record bulk insert:

@isTest
private class OpportunityTriggerTest {

    @TestSetup
    static void setup() {
        Account acc = TestDataFactory.createAccount();
        TestDataFactory.createContacts(acc.Id, 2, null, true);
    }

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

        List<Opportunity> opps = TestDataFactory.createOpportunities(
            acc.Id,
            200,
            new Map<SObjectField, Object>{ Opportunity.Amount => 250000 },
            false
        );

        Test.startTest();
        insert opps;
        Test.stopTest();

        List<Opportunity> results = [
            SELECT Id, NextStep FROM Opportunity WHERE Id IN :opps
        ];
        Assert.areEqual(200, results.size(), 'All 200 opportunities should insert');
        for (Opportunity o : results) {
            Assert.areEqual('Executive review', o.NextStep,
                'Deals over 100,000 should be routed to executive review');
        }
    }

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

        List<Opportunity> opps = TestDataFactory.createOpportunities(
            acc.Id, 1, new Map<SObjectField, Object>{ Opportunity.Amount => 5000 }, false
        );

        Test.startTest();
        insert opps;
        Test.stopTest();

        Opportunity result = [SELECT NextStep FROM Opportunity WHERE Id = :opps[0].Id];
        Assert.isNull(result.NextStep, 'Small deals should not get a next step');
    }
}

Each test method reads as a scenario: get the account, create opportunities with one field changed, run the DML, assert the outcome. All the record plumbing lives in the factory.

The annotations that make this work

Annotation / methodWhere it goesWhat it does
@isTest on a classFactory class and test classesMarks the class as test code. It doesn't count toward the org's Apex code size limit and can only run in test context.
@isTest on a methodEach test methodMarks the method as a test the runner executes.
@TestSetupOne static method per test classRuns once before the class's tests. Each test method gets its own fresh copy of those records, and changes in one test don't leak into another.
@isTest(SeeAllData=true)Class or method (avoid)Gives the test access to real org data. Can't be combined with @TestSetup in the same class.
Test.startTest() / Test.stopTest()Inside a test methodGives the code between them a fresh set of governor limits, and forces queued async work (future, queueable, batch) to finish at stopTest().

A factory annotated with @isTest can only be called from test code. That's deliberate: you never want production code to be able to generate fake Accounts.

Methods on the factory must be public (or global) so other test classes can call them. Don't annotate the factory's helper methods with @isTest themselves. They are utilities, not tests.

Test data must not depend on org data

Since API version 24.0, Apex tests can't see the org's existing records by default. A test that runs [SELECT Id FROM Account LIMIT 1] without creating an Account first gets zero rows and fails with List has no rows for assignment to SObject.

Keep that default. Tests that read real data break in predictable ways:

  • Sandbox refreshes and empty scratch orgs. The record the test expects doesn't exist, so deployment to a fresh environment fails.
  • Data changes in production. Someone deactivates the "Test Account" the test relied on, and the next deployment is blocked.
  • Non-repeatable results. The same test passes in one org and fails in another because the data differs.

A small set of setup and metadata objects stays visible without SeeAllData, including User, Profile, RecordType, Organization and ApexClass. So querying a Profile to build a test user is fine:

public static User createUser(String profileName) {
    Profile p = [SELECT Id FROM Profile WHERE Name = :profileName LIMIT 1];
    Integer n = nextNumber();
    User u = new User(
        ProfileId         = p.Id,
        LastName          = 'Tester' + n,
        Email             = 'tester' + n + '@example.com',
        Username          = 'tester' + n + '.' + System.currentTimeMillis() + '@example.com',
        Alias             = 'tst' + n,
        TimeZoneSidKey    = 'America/Los_Angeles',
        LocaleSidKey      = 'en_US',
        EmailEncodingKey  = 'UTF-8',
        LanguageLocaleKey = 'en_US'
    );
    insert u;
    return u;
}

Usernames must be unique across all Salesforce orgs, which is why the example appends a timestamp. Inserting a User and a non-setup record (like an Account) in the same transaction throws MIXED_DML_OPERATION. Wrapping one of them in System.runAs() avoids it.

The rare legitimate use of SeeAllData=true is for objects you can't create in a test, such as some standard price book scenarios in older code. For price books, Test.getStandardPricebookId() removes even that need.

Bulk creation for trigger tests

Triggers receive records in chunks of up to 200. A trigger that queries or runs DML inside a loop will pass a one-record test and fail in production when a data loader pushes 10,000 rows. Bulk tests catch that before deployment.

The factory makes bulk tests one line of setup. Three counts are worth testing:

Record countWhat it proves
1The basic logic works.
200The trigger handles a full chunk without hitting SOQL (100) or DML (150) limits.
201The trigger runs twice in one transaction. Static variables and recursion guards behave across chunks.

The 201 case catches a class of bug that 200 misses: a static "already ran" flag that skips the second chunk entirely. For the patterns that keep triggers under limits in the first place, see the Apex bulkification guide.

Always do the bulk DML between Test.startTest() and Test.stopTest(). Setup DML in the factory then uses one set of limits, and the code under test gets its own fresh set, so a limit failure points at the trigger and not the setup.

Common mistakes with factories

Putting assertions in the factory. The factory builds data. Tests decide what's correct. Mixing the two makes failures hard to read.

Hard-coding record type names or picklist values that admins change. If a test depends on a specific record type, query it with Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName() and pass the Id as an override.

One giant createEverything() method. It creates records the test doesn't need, slows the test run, and hides dependencies. Keep methods per object and let tests compose them.

Inserting one record at a time in a loop. A factory that calls insert inside a for loop will hit the 150 DML statement limit as soon as someone asks for 200 records.

Chasing 75% coverage with the factory. Salesforce requires 75% code coverage to deploy, but coverage without assertions proves nothing. The factory makes good assertions easier to write. It doesn't replace them. Apex Test Classes: Beyond 75% Code Coverage covers what to assert and why.

Going further: async tests, System.runAs and the Assert class

A factory covers the setup half of testing. The harder parts are usually in the test methods:

  • Async code. Queueable, batch and future methods only finish at Test.stopTest(), and chained queueables behave differently in tests than in production.
  • System.runAs. Testing sharing rules, permission sets and profile-based logic means running code as a specific user, which pairs with a createUser() factory method.
  • The Assert class. Introduced in Winter '23, Assert.areEqual, Assert.isTrue, Assert.isNull and Assert.fail read more clearly than the older System.assertEquals family.
  • Callout mocks. Tests can't make real HTTP callouts, so any integration code needs HttpCalloutMock implementations.

Salesforce Casts' Apex Test Fest course covers async tests, System.runAs, the Assert class and callout mocks. As with every course on the platform, the code is written live in a real org with no slide decks, and it's in a GitHub repo you can clone. If your factory will feed trigger tests, the free Apex Triggers Framework 101 course (8 episodes, about half an hour) shows the trigger structure those tests are written against.

FAQ

Should the test data factory class be annotated with @isTest?

Yes. An @isTest class doesn't count toward your org's Apex code size limit and can only be called from test code, so production logic can never create fake records through it. Make the methods public static so any test class can call them.

What's the difference between @TestSetup and a test data factory?

They do different jobs and work best together. The factory defines how to build valid records. @TestSetup decides when to build them: once per test class, with a fresh copy for each test method. Call factory methods from inside your @TestSetup method.

Should the factory insert records or just return them?

Offer both through a doInsert parameter. Inserted records suit tests that need existing data, like an Account to hang Opportunities on. Uninserted records let the test do the insert itself between Test.startTest() and Test.stopTest(), which is what you want when testing a before-insert or after-insert trigger.

Can my test use records that already exist in the org?

Not by default, and you shouldn't switch that on. Since API version 24.0, tests only see the records they create, plus a few setup objects such as User, Profile and RecordType. Tests that depend on real data fail after sandbox refreshes and in scratch orgs.

How many records should a bulk trigger test create?

Use 200 to prove the trigger handles a full chunk within governor limits, and 201 to make sure it behaves correctly when it fires twice in one transaction. A factory method that takes a count makes both cases a one-line change.

Does Salesforce Casts teach Apex testing?

Yes. Apex Test Fest covers async tests, System.runAs, the Assert class and callout mocks. Every plan unlocks every course, so the testing course comes with the Apex, trigger and integration courses. Plans are listed on the pricing page.

Next step

Copy the TestDataFactory class above into a sandbox, add whatever fields your org's validation rules require, and rewrite one existing test class to use it. If you want to see async tests, System.runAs and callout mocks built step by step in a real org, start with Apex Test Fest.

Learn it by building it

Every course, every code repository, the discussion group and certificates of completion โ€” one subscription.

Keep going

Keep me in the loop!

Email me when a new episode is published (promise, I will not spam you)

You're signing up to receive emails from Salesforce Casts