Sub topic 7
Creating test data: factories, @TestSetup and avoiding SeeAllData
This chapter assumes you can write basic Apex test classes with @isTest methods and use the Assert class. It covers how to build the records your tests need, how to share them across methods, and why tests should not depend on the data already in the org.
Why tests create their own data
Apex tests run in a rolled-back transaction. Any records a test inserts disappear when the test finishes, so tests can create data freely without polluting the org.
A test that reads existing org data is fragile. It can pass in a sandbox and fail in production because the records differ. By default, test methods cannot see existing data (except setup objects such as User). This isolation is what you want.
A test data factory
A factory is a class that builds records in one place. Marking it @isTest keeps it out of the org's code size limit, and it cannot be called from non-test code.
@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,
AnnualRevenue = 500
));
}
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 = 'Contact ' + i,
AccountId = a.Id
));
}
}
insert contacts;
return contacts;
}
}The doInsert flag lets a test change field values before inserting. A factory also gives you one place to fix things when a new required field or validation rule breaks every test.
Sharing data with @TestSetup
A method annotated @TestSetup runs once before the test methods in the class. Each test method then gets its own fresh copy of that data, because changes made by one method are rolled back before the next runs.
@isTest
private class AccountServiceTest {
@TestSetup
static void makeData() {
TestDataFactory.createAccounts(5, true);
}
@isTest
static void readsSharedAccounts() {
List<Account> accounts = [SELECT Id, Name FROM Account];
Assert.areEqual(5, accounts.size(), 'Setup should create five accounts');
}
@isTest
static void changesAreIsolated() {
delete [SELECT Id FROM Account LIMIT 1];
Assert.areEqual(4, [SELECT COUNT() FROM Account], 'One account deleted in this test');
}
}If changesAreIsolated runs first, readsSharedAccounts still sees five accounts.
Query the records again inside each test method. Variables set in the setup method are not available to the test methods.
Choosing an approach
| Approach | Use when | Trade-off |
|---|---|---|
| Create data inside the test | Only one method needs it | Repeated code if several methods need it |
| Factory class | Many classes build the same records | Must be kept current as the schema changes |
| `@TestSetup` | Several methods in one class share records | Setup runs for every class that has it, and failures there fail the whole class |
| `SeeAllData=true` | Rare cases that need org-only data | Tests become unpredictable |
Common mistakes
- Hard-coding record IDs or names that exist only in one org.
- Querying without a filter and assuming only your records exist. Filter by IDs you created.
- Putting assertions in the factory. Keep the factory for building data only.
- Creating more data in
@TestSetupthan the tests need. Large setups slow every run.
Exercise
A test passes in your sandbox but fails after deployment to production. It queries [SELECT Id FROM Account WHERE Name = 'Acme' LIMIT 1] and uses the result. What is the likely cause, and how do you fix it?
Show answer
The test relies on an existing "Acme" record, probably through SeeAllData=true or a record that only exists in the sandbox. By default a test cannot see org data, so the fix is to create the Account in the test, in a factory, or in @TestSetup, and remove SeeAllData=true.
Exercise
Two test methods share data from @TestSetup. The first deletes a record. Does the second method see the deletion?
Show answer
No. The platform rolls back each test method's changes, so every method starts with the data exactly as @TestSetup created it.