Salesforce Framework

Test Data Builders

Test data builder framework that keeps Apex tests resilient as required fields and object relationships change.

Purpose

Before the framework, adding a required field to a shared object such as Account could break every test that created one. Tests also repeated default values and manually assembled related records, making setup brittle and difficult to maintain.

Implementation

Builders for each object centralize defaults for required and common fields. Tests specify only the values relevant to the scenario, while builders create and connect dependent records as needed.

The framework tracks unsaved records and their lookup relationships, then coordinates grouped inserts and any needed subsequent updates when saving related records.

@IsTest
class ExampleTest {
    @IsTest
    static void testContact() {
        Account accountRecord = new AccountBuilder()
            .recordType(AccountConstant.RECORD_TYPE_HOUSEHOLD)
            .build();

        Contact contactRecord = new ContactBuilder()
            .account(accountRecord)
            .save();

        // Contact is linked to account and all required fields are populated
    }
}

Test benefits

  • Changes to required fields and default values are updated once in the appropriate builder.
  • Tests focus on the values and relationships that matter to the scenario.
  • Builders coordinate related records and avoid repeated setup for individual records.