Framework to setup Apex test data in a highly flexible and readable way using the Test Data Builder pattern.
Test Data Builder framework to setup test data for complex Apex integration tests in a concise, readable and flexible way.
Setting up test data for complex Apex integration tests is not easy, because you need to..:
__c
all over the placeMap<Id, SObject>
to keep track of related recordsTestFactories as used by many developers and recommended by Salesforce.com can help to minimize ugly setup code by moving it to seperate classes. But over the time those classes tend to accumulate complexity and redundant spaghetti code.
In the world of Enterprise software outside of Salesforce.com there are experts that have created patterns for flexible and readable (fluent, concise) test data generation. Among them the most notable is Nat Pryce who wrote a great book about testing and somewhat invented the Test Data Builder pattern.
apex-domainbuilder brings those ideas to Apex testing:
@IsTest
public class Account_t extends DomainBuilder {
public Account_t() {
super(Account.SObjectType);
name('Acme Corp');
}
public Account_t name(String value) {
return (Account_t) set(Account.Name, value);
}
public Account_t add(Opportunity_t opp) {
return (Account_t) opp.setParent(Opportunity.AccountId, this);
}
public Account_t add(Contact_t con) {
return (Account_t) con.setParent(Contact.AccountId, this);
}
}
fflib_SObjectUnitOfWork
for the DML all test run dramatically faster. @IsTest
private static void easyTestDataCreation() {
// Setup
Contact_t jack = new Contact_t().first('Jack').last('Harris');
new Account_t()
.name('Acme Corp')
.add( new Opportunity_t()
.amount(1000)
.closes(2019, 12)
.contact(jack))
.persist();
// Exercise
...
// Verify
...
}