Test Data Factories
By the end of this lesson, you'll be able to:
- Extract repeated test-data setup into a reusable factory method
- Explain why duplicated setup code across test methods is worth refactoring
- Apply Module 12/17/22/23's refactoring habit specifically to test code
Prerequisites: "Testing Triggers: Bulk and Edge Cases"
Spotting duplication across test methods
@isTest
static void test1() {
Account acc = new Account(Name = 'Test Account', Industry = 'Technology');
insert acc;
// ...
}
@isTest
static void test2() {
Account acc = new Account(Name = 'Test Account', Industry = 'Technology');
insert acc;
// ...
}
Every test method needing a valid Account repeats the exact same setup — the same duplication problem Modules 12, 17, 22, and 23 each closed out by extracting a shared private method, now showing up in test code specifically.
Extracting a factory method
@isTest
private class AccountRollupServiceTest {
private static Account createTestAccount() {
Account acc = new Account(Name = 'Test Account', Industry = 'Technology');
insert acc;
return acc;
}
@isTest
static void test1() {
Account acc = createTestAccount();
// ...
}
@isTest
static void test2() {
Account acc = createTestAccount();
// ...
}
}
createTestAccount() is private static — callable directly from any @isTest static method in the same class, exactly like the trigger handler's private helpers from Module 22. Any future change to what a "valid test Account" needs happens in exactly one place.
A shared factory class for reuse across multiple test classes
@isTest
public class TestDataFactory {
public static Account createAccount(String name) {
Account acc = new Account(Name = name, Industry = 'Technology');
insert acc;
return acc;
}
public static Book__c createBook(String title) {
return new Book__c(Title__c = title, ISBN__c = '000-0-000-00000-0', Is_Checked_Out__c = false);
}
}
// used from any test class:
Account acc = TestDataFactory.createAccount('Riverbend Farms');
For data patterns reused across multiple test classes (not just within one), a dedicated @isTest public class TestDataFactory avoids duplicating the same setup logic across every test file in the org — the natural next step once a single class's private helper isn't enough.
Exercise
Extract a private static createTestBook() factory method that inserts and returns a valid Book__c, then use it in a test method.
Show hint
private static Book__c createTestBook() { ...; insert book; return book; }
Test Data Factories Quiz
My Notes
Log in to keep private notes on this lesson.
Questions about this lesson
No questions yet — be the first to ask.
Log in to ask a question about this lesson.
Summary
Just like production code, test code accumulates duplication — a test data factory extracts the repeated "build a valid test record" logic into one reusable method, exactly the refactoring instinct from every project module's closing lesson.