Snippet
Apex
25 Apr 2026
Test data factory, the minimal version
One class, builder-style defaults, no framework — the 80% of a test factory most orgs actually need.
@isTest
public class TestFactory {
public static Account account() { return account('Acme ' + counter()); }
public static Account account(String name) {
return new Account(Name = name, Industry = 'Technology');
}
public static Contact contact(Id accountId) {
return new Contact(FirstName = 'Test', LastName = 'Person ' + counter(),
AccountId = accountId,
Email = 'test' + counter() + '@example.com');
}
public static List<Account> accounts(Integer n) {
List<Account> out = new List<Account>();
for (Integer i = 0; i < n; i++) out.add(account());
return out;
}
static Integer seq = 0;
static Integer counter() { return ++seq; }
}One class, builder-style defaults, no framework — the 80% of a test factory most orgs actually need.
Gotchas
Return unsaved records and let the test decide when to insert — tests that need Ids call insert themselves, tests that don't stay fast. The counter keeps unique fields unique across a 200-record build.