This is an freestanding version of the Nebula framework's Test SObject Builder, used to generate test records for unit tests - it has been updated to remove any dependencies on the rest of the Nebula framework.
TestSObjectBuilder.cls is the primary focus of this project - it implements the interface ITestSObjectBuilder. This provides a framework for definining classes that can be used for test data generation.
TestSObjectBuilder is defined as a test class - test classes cannot be abstract, so the subclass, TestSObjectBuilder.Base, has been created. This allows TestSObjectBuilder to be marked as @isTest while still providing reusable code via an abstract class.
- To leverage TestSObjectBuilder, create a class that extends TestSObjectBuilder.Base. The recommended approach is to create 1 class per SObject type, with 1 or more subclasses (depending on your needs). For example, you might have
- Class: TestAccountBuilder - 1 outer class that handles creating any type of test data for the Account object
- Subclass: Base - a very basic the most simple way to insert a test record
- Subclass: RecordTypeX - another subclass that creates an account with a specific record type
- Class: TestAccountBuilder - 1 outer class that handles creating any type of test data for the Account object
- For each subclass that you create to extend TestSObjectBuilder.Base, there are 2 methods that you must override
- getSObjectType() - defines what SObject type is being created
- getDefaultFieldsAndValues - defines what fields need to be set in order to create a test record. This will be specific to your org, based on any custom fields, validation rules, etc that have been added.
- When you need to create a test account, call the build method on your class.
Account myTestAccount = TestAccountBuilder.build();
2 sample classes have been included in the repo
- Sample_TestAccountBuilder.cls - demonstrates the most basic implementation of TestSObjectBuilder.Base
- Sample_TestContactBuilder.cls - demonstrates how to make additional fields, like contact.AccountId, required to be populated by adding a new constructor with an account ID parameter