Sub topic 6
Building a reusable test data factory
This chapter assumes you can write an Apex test class with @IsTest methods, run SOQL and DML, and use @TestSetup and the Assert class. It also assumes you know that test data is rolled back after each test. Here you will build a small, reusable test data factory. You will also see where factories go wrong.
Why a factory
Without a shared helper, every test class builds its own records. That causes three recurring problems:
- Duplication. Ten test classes each set
Name,Industry, andBillingCountryby hand. - Fragile tests. A new required field or validation rule breaks every test class at once. You fix the same line in many places.
- Noise. Setup code hides what the test is actually checking.
A test data factory is one @IsTest class whose static methods create records with valid default values. Tests call the factory and override only the fields that matter to that test.
Rules for a factory class
A factory is a normal Apex class with a few constraints.
- Annotate the class with
@IsTest. Code in an@IsTestclass does not count against your org's code size limit, and production code cannot call it. - Keep methods
public static. A class annotated@IsTestcan have non-test helper methods, and other test classes can call them. - Do not put
@IsTeston the factory's helper methods. They are not tests, so they should not run as tests. - Never hard-code record IDs, and never use
@SeeAllData. The factory creates everything it needs.
A first version
Start with the simplest useful shape: one method per object, with a parameter for the count.
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count) {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < count; i++) {
accounts.add(new Account(
Name = 'Test Account ' + i,
Industry = 'Technology'
));
}
return accounts;
}
}Notice that this method does not insert the records. That choice matters, and the next section explains it.
Insert or not: give the caller the choice
A factory has to decide whether it performs DML. There are two common designs.
| Design | Benefit | Cost |
|---|---|---|
| Always insert | Short test code | Cannot test code that needs unsaved records, and cannot adjust fields before saving |
| Never insert | Caller controls fields and timing | Caller writes one extra `insert` line |
| Overload with a `doInsert` flag | Both uses are covered | Slightly larger API |
The third design is usually the best fit. Each method takes a Boolean, and the plain version returns unsaved records.
@IsTest
public class TestDataFactory {
public static List<Account> createAccounts(Integer count) {
return createAccounts(count, false);
}
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',
AnnualRevenue = 1000
));
}
if (doInsert) {
insert accounts;
}
return accounts;
}
public static List<Contact> createContacts(List<Account> parents, Integer perAccount, Boolean doInsert) {
List<Contact> contacts = new List<Contact>();
for (Account parent : parents) {
for (Integer i = 0; i < perAccount; i++) {
contacts.add(new Contact(
AccountId = parent.Id,
FirstName = 'Test',
LastName = 'Contact ' + parent.Name + ' ' + i
));
}
}
if (doInsert) {
insert contacts;
}
return contacts;
}
}createContacts needs saved parents, because parent.Id is null until the accounts are inserted. If you pass unsaved accounts, every contact gets a null AccountId and silently becomes an orphan. The factory does not stop you, so the test must insert the accounts first.
Using the factory in a test
The test below uses the factory to build 200 accounts, then changes one field on a subset before saving. This is the main advantage of the "return unsaved records" design.
public class AccountRatingService {
public static void markHot(List<Account> accounts) {
for (Account a : accounts) {
if (a.AnnualRevenue != null && a.AnnualRevenue >= 1000000) {
a.Rating = 'Hot';
}
}
update accounts;
}
}
@IsTest
private class AccountRatingServiceTest {
@IsTest
static void marksOnlyHighRevenueAccounts() {
List<Account> accounts = TestDataFactory.createAccounts(200);
for (Integer i = 0; i < accounts.size(); i++) {
if (Math.mod(i, 4) == 0) {
accounts[i].AnnualRevenue = 5000000;
}
}
insert accounts;
Test.startTest();
AccountRatingService.markHot(accounts);
Test.stopTest();
Integer hot = [SELECT COUNT() FROM Account WHERE Rating = 'Hot'];
Assert.areEqual(50, hot, 'Every fourth account has high revenue, so 50 of 200 should be Hot');
}
}The test states its own business rule (every fourth account is high revenue) in the test body. The factory supplies only the boring defaults. A reader sees the relevant data without opening the factory.
Combining the factory with @TestSetup
@TestSetup runs once per test class, and each test method then starts from a fresh copy of that data. The factory fits naturally inside it.
@IsTest
private class ContactCountTest {
@TestSetup
static void setup() {
List<Account> accounts = TestDataFactory.createAccounts(5, true);
TestDataFactory.createContacts(accounts, 3, true);
}
@IsTest
static void everyAccountHasThreeContacts() {
List<Account> accounts = [
SELECT Id, (SELECT Id FROM Contacts)
FROM Account
];
Assert.areEqual(5, accounts.size(), 'Setup should create 5 accounts');
for (Account a : accounts) {
Assert.areEqual(3, a.Contacts.size(), 'Each account should have 3 contacts');
}
}
}Use @TestSetup for data that most methods in the class need. Build data inside the test method when only that test needs it, or when it needs a different shape from the shared data.
Unique values and required fields
Some fields must be unique, such as User.Username and any custom field marked unique. A factory has to generate distinct values on every call, or the second call fails with a DUPLICATE_VALUE error.
The User factory below combines a counter with a random suffix. It looks up the profile by name, which is more stable than a hard-coded ID.
@IsTest
public class UserTestFactory {
private static Integer counter = 0;
public static User createUser(String profileName, Boolean doInsert) {
Profile p = [SELECT Id FROM Profile WHERE Name = :profileName LIMIT 1];
counter++;
String unique = String.valueOf(counter) + String.valueOf(Crypto.getRandomInteger()).replace('-', 'n');
User u = new User(
Alias = 'u' + String.valueOf(counter).leftPad(3, '0'),
Email = 'user' + unique + '@example.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester' + counter,
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'user' + unique + '@example.com.test'
);
if (doInsert) {
insert u;
}
return u;
}
}Static variables reset between test methods, so the counter restarts for each test. The random part keeps usernames unique across tests and across orgs, because usernames must be unique across all of Salesforce.
Optional overrides with a field map
A method per object with many parameters becomes hard to call. A common compromise is an overload that accepts a map of field values to apply on top of the defaults.
@IsTest
public class TestDataFactory {
public static Account createAccount(Map<String, Object> overrides, Boolean doInsert) {
Account a = new Account(Name = 'Test Account', Industry = 'Technology');
if (overrides != null) {
for (String fieldName : overrides.keySet()) {
a.put(fieldName, overrides.get(fieldName));
}
}
if (doInsert) {
insert a;
}
return a;
}
}A call looks like this:
Account big = TestDataFactory.createAccount(
new Map<String, Object>{ 'AnnualRevenue' => 9000000, 'Rating' => 'Cold' },
true
);The cost is type safety. A misspelled field name compiles, then fails at runtime with an SObjectException. Use the map form for objects with many fields, and plain parameters or direct assignment for small ones.
Common errors
- Orphaned children. Building child records from unsaved parents leaves lookup fields null. Insert the parents first, or assert on the
AccountIdbefore you continue. - Governor limit use in the factory. A factory that runs a SOQL query per call, such as the profile lookup above, counts toward the limit of 100 queries in a transaction. Calling
createUserin a loop of 101 iterations fails. Query once and reuse the result, or create users in bulk. - One method that does everything. A method like
createEverything()hides what a test depends on, and it makes tests slow. Keep methods small and composable. - Hidden assumptions in defaults. If a factory sets
AnnualRevenue = 1000and your code branches on revenue, the test result depends on a value the reader cannot see. Set values that drive the behavior explicitly inside the test. - Silent coupling to org configuration. A required custom field, validation rule, or flow added later can break the factory. That is a reason to have one factory. You fix it once.
- Using
@SeeAllData=trueto avoid building data. The test then depends on whatever exists in the org. Build the data instead.
Checking the factory itself
The factory is code, so it can break. A cheap safeguard is one small test that confirms the defaults still produce valid, insertable records.
@IsTest
private class TestDataFactoryTest {
@IsTest
static void defaultsAreInsertable() {
List<Account> accounts = TestDataFactory.createAccounts(200, true);
List<Contact> contacts = TestDataFactory.createContacts(accounts, 1, true);
Assert.areEqual(200, [SELECT COUNT() FROM Account], 'All 200 accounts should be saved');
Assert.areEqual(200, [SELECT COUNT() FROM Contact], 'One contact per account should be saved');
Assert.isNotNull(contacts[0].AccountId, 'Contacts should be linked to their accounts');
}
}When a new validation rule breaks the defaults, this one test fails first and points straight at the factory.
Design flow
Summary of guidelines
- Mark the factory class
@IsTest, and keep its helper methodspublic staticwithout@IsTest. - Return unsaved records by default, with an option to insert.
- Generate unique values for fields that require them.
- Set values that drive the behavior under test inside the test, not in the factory defaults.
- Avoid queries and DML inside loops in the factory.
- Add one small test that proves the factory's defaults still save.
Exercise
A test calls TestDataFactory.createContacts(TestDataFactory.createAccounts(3), 2, true), where createAccounts(3) returns unsaved accounts. The insert succeeds, but a later assertion that every contact has a parent account fails. What is the cause, and how do you fix the test?
Show answer
The accounts were never inserted, so parent.Id was null when the contacts were built, and every contact was saved with a null AccountId. Fix it by creating the accounts with createAccounts(3, true) (or inserting the list) before passing them to createContacts. You can also add Assert.isNotNull(contact.AccountId, ...) to catch the problem early.
Exercise
Why is it a bad idea to hard-code AnnualRevenue = 1000 in a factory default and then write a test for a rule that triggers at revenue of 1,000 or more, without setting the field in the test?
Show answer
The test outcome depends on a default value that is hidden in another class. A change to the factory default would change the test result without any edit to the test. The test should set AnnualRevenue explicitly so the input that drives the behavior is visible where the assertion is.