Test Data Builder Framework
D'fflib ships a complete Test Data Builder Framework to quickly set up typed, fluent test data — including parent and child relations, formula fields and read-only fields — without touching the database.
Highlights & takeaways
The Test Data Builder Framework centralises all test data construction behind a single, typed, fluent API. Three output modes cover every testing scenario: pure in-memory mocking (with full formula and read-only field support via a JSON serialisation trick), fake-ID mocking with auto-propagated relationships, and direct database insertion via the Unit of Work. The consistent naming convention, built-in default values and deduplication make test data creation fast, DRY and maintainable across the entire team.
Most Salesforce projects eventually accumulate the same pattern: new Account( Name = 'Test Account' ) scattered
across hundreds of test methods. When a required field is added to the object, every test breaks. When a
relationship changes, the fix is manual and error-prone. When a developer joins the team, they copy the nearest
example and introduce yet another variation of the same construction — often missing required fields, duplicating
defaults, or inserting records that could have been mocked.
The Test Data Builder Framework eliminates this entirely. All test data construction lives in one place, behind a typed fluent API that reads like a sentence, handles relationships automatically, and gives full control over what ends up in the database — and what doesn't.
The framework consists of five collaborating classes:
| Class | Responsibility |
|---|---|
TestFactory | Single static entry point — anAccount(), aCase(), aUser(), etc. |
DOM_*Test.Builder | Project-specific builders — one per SObject, living in the domain test class |
dfflib_UT_TestFactoryData | Deduplication key definitions and uniqueness cache |
dfflib_UT_SObjectFactory | Core engine — node graph, JSON serialisation, cache, mock() / save() |
dfflib_UT_Replacers | Dynamic merge-field values — CounterReplacer, RandomReplacer |
A companion class dfflib_UT_Utils provides additional utilities for common test scenarios (see below).
How to write unit tests with D'fflib
A step-by-step introduction on how to leverage the framework in practice — mocking layers, structuring test data and writing proper single-responsibility assertions.
Visit code examples in repository
Have a look at TestFactory and Builders in domains in our repo to explore the code, methods and comments.
A brief introduction
The framework exposes three output modes, each suited to a different testing scenario:
| Mode | Method | DB hit? | IDs populated? | Formula & read-only fields? | Use when... |
|---|---|---|---|---|---|
| Pure mock | .mock() | ✗ | ✗ | ✓ | Unit testing a service or domain method — no database needed |
| Mock with IDs | .mockWithIds() | ✗ | ✓ (fake) | ✓ | Unit testing logic that reads .Id or traverses lookup fields |
| Database insert | .save() | ✓ | ✓ (real) | ✗ | Integration tests or @TestSetup methods that require real records |
Prefer mocking over inserting
Wherever the test logic does not require a real database record, prefer .mock() or .mockWithIds().
This eliminates DML governor limit consumption, removes the need for @TestSetup, and makes tests
significantly faster — especially when combined with D'fflib's layer mocking via defineMock().
Single entry point
All test data construction starts from TestFactory — a class of static factory methods, one per
supported SObject. This gives every developer on the team the same starting point, with IDE autocomplete
guiding them to the right builder.
TestFactory.anAccount() // → DOM_AccountsTest.Builder
TestFactory.aCase() // → DOM_CasesTest.Builder
TestFactory.aUser() // → DOM_UsersTest.Builder (pre-configured with asDefault())
TestFactory.anOpportunity() // → DOM_OpportunitiesTest.Builder
TestFactory.aProduct() // → DOM_ProductsTest.BuilderNote that aUser() automatically calls .asDefault(), pre-populating locale, timezone and encoding
fields — the most common source of missing required fields on User records in test classes.
Fluent builder API with consistent naming conventions
Every builder follows the same naming convention, making the intent of each method immediately readable and predictable across the entire codebase:
| Prefix | Purpose | Example |
|---|---|---|
as | Scenario shortcut — sets multiple fields at once | asDefault(), asStandard( 'Product A' ), asTest() |
for | Parent lookup — links to another builder | forAccount( accountBuilder ) |
add | Child relationship — attaches a child builder | addContact( contactBuilder ) |
is | Boolean field | isClosed( true ), isActive() |
with | Any other field — typed by field token | withName( 'Acme' ), withCloseDate( today ) |
Named with*() methods use SObjectField tokens for compile-time safety and IDE navigation.
A generic with( SObjectField, value ) overload is also available as a catch-all for fields
that don't have a dedicated named method:
// Named method — preferred for readability
TestFactory.anAccount().withName( 'Acme Corp' )
// Generic overload — useful for less common fields
TestFactory.anAccount().with( Account.Rating, 'Hot' )A string-based escape hatch exists on some builders for fields where a token is not available at compile time:
// String-based fallback — use only when SObjectField token is unavailable
TestFactory.aCase().with( 'CustomField__c', 'value' )All builder methods, except the inherited methods mock(), mockWithIds() and save(), return this, enabling full method chaining:
Account acc = ( Account ) TestFactory.anAccount()
.withName( 'Acme Corp' )
.mock();Relationship graph — parents, children, bidirectional
The framework models the full relationship graph between records. Parent lookups and child collections are registered on the builder and resolved automatically — whether mocking or saving.
Child relationships use addChild( SObjectField lookupOnChild, BuilderBase child ), where the
field token is the lookup field on the child pointing back to the parent:
// DOM_AccountsTest.Builder — Contact.AccountId is the lookup on Contact pointing to Account
public DOM_AccountsTest.Builder addContact( DOM_ContactsTest.Builder cBuilder ){
addChild( Contact.AccountId, cBuilder );
return this;
}Parent relationships use setParent( SObjectField lookupOnThis, BuilderBase parent ):
// DOM_CasesTest.Builder — Case.AccountId is the lookup on Case pointing to Account
public DOM_CasesTest.Builder forAccount( DOM_AccountsTest.Builder builder ){
setParent( Case.AccountId, builder );
return this;
}When saving, the framework delegates to the Unit of Work and resolves the correct DML insertion order
automatically — no manual registerNew / registerRelationship calls needed.
When calling .mockWithIds(), the framework traverses the full relationship tree, assigns fake IDs
(via fflib_IDGenerator) to every node, and populates all lookup fields bidirectionally. A
cycle-detection guard (stack depth limit of 5) prevents infinite recursion on circular references.
// Fake IDs auto-assigned and propagated through the full relationship tree
DOM_AccountsTest.Builder accBuilder = TestFactory.anAccount();
DOM_ContactsTest.Builder conBuilder = TestFactory.aContact()
.forAccount( accBuilder );
Contact con = ( Contact ) conBuilder.mockWithIds();
// Both records have fake IDs; Contact.AccountId is populated
System.Assert.isNotNull( con.Id );
System.Assert.isNotNull( con.AccountId );// Full database insertion — relationships resolved automatically via Unit of Work
Account acc = ( Account ) TestFactory.anAccount()
.addContact( TestFactory.aContact().withName( 'Jane Doe' ) )
.save();
// acc.Id is a real Salesforce ID; the Contact is inserted and linked
System.Assert.isNotNull( acc.Id );// Full hierarchy: Account → Opportunity → OpportunityLineItem ← Product
DOM_AccountsTest.Builder accBuilder = TestFactory.anAccount()
.withName( 'Acme Corp' );
DOM_ProductsTest.Builder productBuilder = TestFactory.aProduct()
.asStandard( 'Enterprise License' );
Opportunity opp = ( Opportunity ) TestFactory.anOpportunity()
.forAccount( accBuilder )
.addOppLineitem(
TestFactory.anOpportunityLineItem()
.forProduct( productBuilder )
)
.save();Scenario presets via as*() methods
Where applicable, builders expose as*() methods that set a meaningful combination of fields in one
call — keeping test classes readable and preventing callers from having to know which fields constitute
a valid scenario. Not every builder needs an as*() method; they are only added when a meaningful
business scenario warrants it.
// DOM_UsersTest.Builder — asDefault() sets all required locale and encoding fields
public DOM_UsersTest.Builder asDefault(){
set( User.EmailEncodingKey, 'UTF-8' );
set( User.LanguageLocaleKey, 'nl_NL' );
set( User.LocaleSidKey, 'en_US' );
set( User.TimeZoneSidKey, 'Europe/Amsterdam' );
this.isActive( true );
return this;
}as*() methods can also compose other builders, making complex scenarios concise:
// DOM_AccountsTest.Builder — asAdministrative() sets record type + name in one call
public DOM_AccountsTest.Builder asAdministrative(){
forRecordType( TestFactory.aRecordType().withDeveloperName( 'Administrative' ) );
withName( 'Do Not Delete' );
return this;
}
// DOM_ProductsTest.Builder — asStandard() activates the product and adds a standard pricebook entry
public DOM_ProductsTest.Builder asStandard( String productName ){
set( Product2.Name, productName );
isActive();
addEntry( new DOM_PricebookEntriesTest.Builder().forPricebook( new DOM_PricebooksTest.Builder().asTest() ) );
return this;
}When a scenario should always be applied for a given SObject — such as User always needing locale
and encoding fields — pre-wire the as*() call in TestFactory so callers never have to
remember it:
// TestFactory.cls — asDefault() pre-wired, callers get a valid User automatically
public static DOM_UsersTest.Builder aUser(){
return new DOM_UsersTest.Builder().asDefault();
}For fields that must be unique across records, dfflib_UT_Replacers generate dynamic values at evaluation
time — not at definition time. These can be used directly inside as*() methods or set() calls:
CounterReplacer— increments a per-field, per-SObjectType counter each time a record is created.new CounterReplacer( 'Test Account {0}' )→'Test Account 0','Test Account 1', ...RandomReplacer— generates a random alphanumeric string of a given length.new RandomReplacer( 'TEST{0}', 8 )→'TEST47297486'
// Inside an as*() method — unique username and nickname per User record
set( User.Username, new dfflib_UT_Replacers.CounterReplacer( 'unittestuser{0}@fflibfast.com' ) );
set( User.CommunityNickname, new dfflib_UT_Replacers.RandomReplacer( 'TEST{0}', 8 ) );The JSON serialisation trick — formula and read-only fields
This is the most important technical capability of the framework, and the reason .mock() is so
powerful for unit testing.
In Apex, formula fields, rollup summaries, and system-managed fields (like CreatedDate, relationship
objects, or auto-calculated values) cannot be written to directly. Attempting to set them on an SObject
instance throws a runtime exception. This makes it impossible to test logic that reads these fields
without inserting a real record — which is slow, consumes DML limits, and often requires complex setup.
The framework bypasses this restriction entirely. When .mock() is called, the engine:
- Serialises the full node graph (fields, parents, children) to a
Map<String, Object> - Calls
JSON.serialize()on that map - Calls
JSON.deserialize()back to the typed SObject
Apex's JSON deserialiser does not enforce field-level write restrictions. The result is a fully populated SObject instance with formula fields, rollup values, and read-only fields set to whatever values the builder specified — without a single DML operation.
// Opportunity.Amount is auto-calculated from child OLIs — not writable in Apex
// With mock(), it can be set directly on the builder
public DOM_OpportunitiesTest.Builder asWithAmount( Decimal amount ){
set( Opportunity.Name, 'Test Opportunity' );
set( Opportunity.StageName, 'Nieuw' );
set( Opportunity.CloseDate, System.today().addDays( 1 ) );
set( Opportunity.Amount, amount ); // read-only field — populated via mock()
return this;
}
// In the test class — no DML, no SOQL, Amount is populated
Opportunity opp = ( Opportunity ) TestFactory.anOpportunity()
.asWithAmount( 50000 )
.mock();
System.Assert.areEqual( 50000, opp.Amount );// Direct construction — read-only fields cannot be set
Opportunity opp = new Opportunity(
Name = 'Test Opportunity',
StageName = 'Nieuw',
CloseDate = System.today().addDays( 1 )
// Amount = 50000 ← runtime exception: field is not writeable
);
// Only option without the framework: insert child OLIs and re-query
// — costs DML, a SOQL query, and all required fields must be set
insert opp;
opp = [ SELECT Id, Amount FROM Opportunity WHERE Id = :opp.Id ];Why this matters for unit tests
Any method that branches on a formula field, a rollup summary, or a system field can be tested
in full — without a database — by setting it on the builder via an as*() method. This is the
single most impactful reason to adopt .mock() over inline SObject construction for unit tests.
The same trick is applied in dfflib_UT_Utils to construct Database.SaveResult, Database.DeleteResult
and Database.UndeleteResult instances — system types that Apex forbids direct construction of
(see Companion utilities).
How it works
How to write unit tests with D'fflib
Step-by-step guidance on structuring test data, mocking layers and writing proper single-responsibility assertions. Click to read more.
Accelerators & Utilities
The full set of D'fflib utility methods and shortcuts — including dfflib_UT_Utils and defineMock().
Click to read more.
Companion utilities
dfflib_UT_Utils provides a set of ready-to-use utility methods for common test scenarios that complement the
builder framework:
dfflib_UT_Utils.getCurrentUser()— returns aUserrecord for the current user without a SOQL query. Useful when aUserinstance is needed as a variable — for example, to pass intoSystem.runAs()or to assert againstUserInfo.getUserId().dfflib_UT_Utils.createSObjectList( SObject sObj, Integer n )— clones an SObject instancentimes. Optionally inserts immediately withcreateSObjectList( sObj, n, true ).dfflib_UT_Utils.getProfile( String name )/getProfileId( String name )— retrieves a Profile by name with internal caching to avoid repeated queries across test methods.dfflib_UT_Utils.createSaveResult( Id recordId, Boolean success, String message )— constructs a mockDatabase.SaveResultinstance. Apex does not allow direct construction ofDatabase.SaveResult— this method applies the same JSON serialisation trick as.mock()to bypass the restriction.dfflib_UT_Utils.createDeleteResult( Id recordId, Boolean success, String message )— same pattern forDatabase.DeleteResult.dfflib_UT_Utils.createUndeleteResult( Id recordId, Boolean success, String message )— same pattern forDatabase.UndeleteResult.
Mock Database results without DML
The createSaveResult, createDeleteResult and createUndeleteResult methods apply the same
JSON serialisation trick as .mock() — bypassing Apex's constructor restrictions on these system types.
This enables testing of error-handling logic that branches on SaveResult.isSuccess() or inspects
SaveResult.getErrors() without performing any actual DML.
// Construct a failed SaveResult — impossible via direct instantiation in Apex
Database.SaveResult failedResult = dfflib_UT_Utils.createSaveResult(
fflib_IDGenerator.generate( Account.SObjectType ),
false,
'Insufficient permissions'
);
System.Assert.isFalse( failedResult.isSuccess() );
System.Assert.areEqual( 'Insufficient permissions', failedResult.getErrors()[ 0 ].getMessage() );