Skip to content
Tutorials Center
My learning

Topics

Lesson 22 of 36 ยท Classes and Testing

Apex Test Data Factories, @TestSetup and Mocking

Build reusable Apex test data with factories and @TestSetup, and isolate code with the Stub API and interface-based test doubles, shown in Apex and Java stand-ins.

Tests that create their data inline get repetitive fast, and tests that call real services get slow and fragile. Two techniques solve both problems. A test data factory builds valid records in one place. Test doubles replace collaborators (a callout, a payment service) with fakes you control. This lesson covers both in Apex and shows the underlying ideas with runnable Java stand-ins. It continues Apex test classes.

Real Apex only runs in an org. Apex code below is read-only; the runnable blocks are Java stand-ins, labelled as such.

A test data factory

A factory is a class annotated @isTest so it does not count toward your org's code size, with static methods that return records. A boolean parameter lets the caller decide whether to insert them.

APEX
@isTest
public class TestDataFactory {

    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 = 'Energy'));
        }
        if (doInsert) {
            insert accounts;
        }
        return accounts;
    }

    public static List<Contact> createContacts(List<Account> accounts, Integer perAccount) {
        List<Contact> contacts = new List<Contact>();
        for (Account a : accounts) {
            for (Integer i = 0; i < perAccount; i++) {
                contacts.add(new Contact(LastName = 'Person ' + i, AccountId = a.Id));
            }
        }
        insert contacts;
        return contacts;
    }
}

Now a test can ask for exactly what it needs:

APEX
@isTest
static void contactCountRollsUp() {
    List<Account> accts = TestDataFactory.createAccounts(200, true);
    TestDataFactory.createContacts(accts, 2);
    // ... run code and assert on 400 contacts
}

If a validation rule later makes Industry required, you change the factory once instead of fifty tests.

@TestSetup

A method annotated @TestSetup runs once before the test methods in a class, and every test method starts from the data it created (changes inside a test method are rolled back, but the setup data is restored for the next one). This is faster than creating the same data in every method.

APEX
@isTest
private class AccountRatingTest {

    @TestSetup
    static void setup() {
        TestDataFactory.createAccounts(50, true);
    }

    @isTest
    static void ratesEveryAccount() {
        List<Account> accts = [SELECT Id FROM Account];
        Assert.areEqual(50, accts.size());
    }
}

Why mock

Some code reaches outside the transaction: HTTP callouts, email sending, an external payment service. Apex tests are not allowed to make real callouts, and you would not want them to. The remedy is to substitute a fake for the dependency. Apex gives you three tools:

  • Test.setMock(HttpCalloutMock.class, new MyMock()) for HTTP callouts (covered in REST callouts).
  • The Stub API (System.StubProvider plus Test.createStub) to build a fake of any class at runtime.
  • Plain interface injection: write your code against an interface and pass a fake from the test. This needs no special API and is the most readable approach.

Interface injection

APEX
public interface PaymentGateway {
    Boolean charge(Decimal amount);
}

public with sharing class CheckoutService {
    private PaymentGateway gateway;

    public CheckoutService(PaymentGateway gateway) {
        this.gateway = gateway;
    }

    public String checkout(Decimal amount) {
        return gateway.charge(amount) ? 'PAID' : 'DECLINED';
    }
}
APEX
@isTest
private class CheckoutServiceTest {
    private class AlwaysDeclines implements PaymentGateway {
        public Boolean charge(Decimal amount) { return false; }
    }

    @isTest
    static void declinedPaymentIsReported() {
        CheckoutService svc = new CheckoutService(new AlwaysDeclines());
        Assert.areEqual('DECLINED', svc.checkout(10));
    }
}

The private inner class is the test double. The production code never knows.

The Stub API

When you cannot or do not want to extract an interface, Test.createStub builds a stand-in for a class. You write a class that implements System.StubProvider and handles every call:

APEX
@isTest
public class GatewayStub implements System.StubProvider {
    public Object handleMethodCall(Object stubbedObject, String methodName, Type returnType,
            List<Type> paramTypes, List<String> paramNames, List<Object> args) {
        if (methodName == 'charge') {
            return true;
        }
        return null;
    }
}
APEX
RealGateway fake = (RealGateway) Test.createStub(RealGateway.class, new GatewayStub());

Stubbing is more flexible but harder to read; prefer interface injection when you control the code.

Try the idea: factory (Java stand-in)

Java Stand-in: a data factory with an insert flag (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Try the idea: injecting a fake (Java stand-in)

Java Stand-in: replacing a payment gateway with a fake (Java)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

The fake also records how it was used, which lets a test assert on interactions as well as results.

Good habits

  • Keep factories valid by default: required fields filled, validation rules satisfied.
  • Create records in bulk lists and insert once; do not insert inside loops.
  • Name the double after its behaviour (AlwaysDeclines), not its type.
  • Do not mock what you do not own in ways the real platform would never behave; check against the real thing in an integration sandbox too.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What is the main benefit of a TestDataFactory class?

    A single factory keeps test data consistent and easy to update when validation rules change.
  2. 2. When does a @TestSetup method run?

    It runs once, and the records it creates are available (restored) to each test method.
  3. 3. Which approach needs no special Apex API to replace a dependency?

    If code depends on an interface you can pass any implementation from the test, including a simple fake class.
  4. 4. Why can't Apex tests make real HTTP callouts?

    Real callouts are blocked in tests; you register a mock response with Test.setMock.

Summary

  • Factories centralise valid test data; @TestSetup shares it across methods.
  • Replace outside dependencies with fakes: interface injection, Test.setMock, or the Stub API.
  • Bulk-create records and insert once.
  • Verify results and, when useful, interactions.

Next: Future Methods