Sub topic 6
Building a reusable test data factory
This chapter assumes you can write an @IsTest class, run SOQL and DML, and know that test data is isolated from the org's real data. You should also know that @TestSetup creates records once per test class.
Why a factory
Without a factory, each test class builds its own Accounts and Contacts. When a validation rule makes a new field required, every class breaks and you edit them all. A test data factory is a single class that builds records with valid default values. Tests call it instead of repeating field assignments.
A factory gives you three things:
- One place to fix when required fields change.
- Shorter tests that show only the values that matter.
- Easy creation of many records for bulk tests.
A minimal factory
Mark the class @IsTest. Code in a class with this annotation does not count against the org's code size limit, and the class can only be called from test code.
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count, Boolean doInsert) {
List<Account> accts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accts.add(new Account(
Name = 'Test Account ' + i,
AnnualRevenue = 1000
));
}
if (doInsert) {
insert accts;
}
return accts;
}
public static List<Contact> createContacts(Integer count, Id accountId, Boolean doInsert) {
List<Contact> contacts = new List<Contact>();
for (Integer i = 0; i < count; i++) {
contacts.add(new Contact(
FirstName = 'Test',
LastName = 'Contact ' + i,
AccountId = accountId
));
}
if (doInsert) {
insert contacts;
}
return contacts;
}
}The doInsert flag matters. With false, the caller can change fields before saving, for example to set AnnualRevenue to a specific value. With true, the caller gets saved records with Ids.
Using the factory in a test
@IsTest
private class AccountServiceFactoryTest {
@IsTest
static void flagsLargeAccount() {
List<Account> accts = TestDataFactory.createAccounts(1, false);
accts[0].AnnualRevenue = 5000000;
insert accts;
Test.startTest();
AccountService.flagLargeAccounts(accts);
Test.stopTest();
Account result = [SELECT Rating FROM Account WHERE Id = :accts[0].Id];
Assert.areEqual('Hot', result.Rating, 'Account over 1,000,000 should be Hot');
}
}The test sets only the field that matters. A reader sees at once that revenue drives the result.
Using the factory with @TestSetup
The factory and @TestSetup work together. The factory builds the records, and @TestSetup saves them once for every test method in the class.
@IsTest
private class ContactCountTest {
@TestSetup
static void setup() {
Account a = TestDataFactory.createAccounts(1, true)[0];
TestDataFactory.createContacts(3, a.Id, true);
}
@IsTest
static void contactsAreLinkedToAccount() {
Account a = [SELECT Id FROM Account LIMIT 1];
Integer total = [SELECT COUNT() FROM Contact WHERE AccountId = :a.Id];
Assert.areEqual(3, total, 'Setup should create three contacts for the account');
}
}Each test method gets a fresh copy of the setup data. Changes one method makes do not reach the next.
Common errors
- Hard-coded unique values. Fields such as
Usernamemust be unique. Build them from a counter orSystem.currentTimeMillis(), as in the earlierSystem.runAsexample. - Missing required fields. If a validation rule or required field changes, the factory throws on insert. Fix it once in the factory.
- Inserting inside a loop. Build the list, then run one
insert. Per-record DML hits governor limits at 200 records. - Relying on org data. The factory must create what the test needs. Avoid
SeeAllData=true.
Exercise
Why does the factory's createAccounts method take a doInsert parameter, and how would you use it to test an account with AnnualRevenue of 5,000,000?
Show answer
With doInsert set to false, the method returns unsaved records. You can set AnnualRevenue = 5000000 on the returned record and then insert it yourself. With true, the records are already saved with default values, so changing a field would require an extra update.
Exercise
A test class calls TestDataFactory.createAccounts(200, true) inside a @TestSetup method. Does a change made to those accounts in one test method appear in the next test method?
Show answer
No. Each test method starts with the data as @TestSetup created it. Changes made in one method are rolled back before the next one runs.