### Convenience Method Example - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/randomizers.md Illustrates a convenience method within a custom mocker class that simplifies applying specific randomizers. This example provides methods to set a random industry or a full account randomizer. ```Apex public class AccountMocker extends TestModule.RecordMocker { public AccountMocker() { super(new Account(Name = 'Test Account')); } public AccountMocker withRandomIndustry() { super.withRandomizer(Account.Industry, new IndustryRandomizer()); return this; } public AccountMocker withAccountRandomizer() { super.withRandomizer(new AccountRandomizer()); return this; } } ``` -------------------------------- ### Implementing Templates with Apex Class Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/templates.md Provides an example of an Apex class that implements the `Template` interface, defining a default account and specific 'enterprise' and 'startup' account templates. ```apex public class Templates implements TestModule.Template { public SObject defaultTemplate() { return new Account(Name = 'Test Account', Industry = 'Technology'); } public Map templates() { return new Map{ 'enterprise' => new Account( Name = 'Enterprise Account', Industry = 'Technology', AnnualRevenue = 1000000 ), 'startup' => new Account( Name = 'Startup Account', Industry = 'Technology', AnnualRevenue = 100000 ) }; } } ``` -------------------------------- ### Apex Test Module for Contact Data Creation Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/README.md This Apex code defines a Test Module for creating and mocking Contact records. It utilizes builder and mocker patterns for flexible test data generation, including template-based creation and custom randomizers for fields like first name and last name. Dependencies include the TestModule framework. ```java @IsTest public class ContactTestModule implements TestModule.BuilderProvider, TestModule.MockerProvider { public static ContactBuilder Builder() { return new ContactBuilder(); } public static ContactMocker Mocker() { return new ContactMocker(); } public class ContactBuilder extends TestModule.RecordBuilder { public ContactBuilder() { super(new Templates()); } public ContactBuilder withFirstName(String firstName) { super.set(Contact.FirstName, firstName); return this; } public ContactBuilder withLastName(String lastName) { super.set(Contact.LastName, lastName); return this; } public ContactBuilder withEmail(String email) { super.set(Contact.Email, email); return this; } public ContactBuilder business() { super.useTemplate('business'); return this; } public ContactBuilder personal() { super.useTemplate('personal'); return this; } public ContactBuilder withContactRandomizer() { super.withRandomizer(new ContactRandomizer()); return this; } } public class ContactMocker extends TestModule.RecordMocker { public ContactMocker() { super(new Contact(FirstName = 'Test', LastName = 'Contact', Email = 'test.contact@example.com')); } public ContactMocker withFirstName(String firstName) { super.set(Contact.FirstName, firstName); return this; } public ContactMocker withLastName(String lastName) { super.set(Contact.LastName, lastName); return this; } public ContactMocker withEmail(String email) { super.set(Contact.Email, email); return this; } public ContactMocker withAccountName(String accountName) { super.set('Account.Name', accountName); return this; } public ContactMocker withFakeId() { super.setFakeId(); return this; } public ContactMocker withContactRandomizer() { super.withRandomizer(new ContactRandomizer()); return this; } } public class Templates implements TestModule.Template { public SObject defaultTemplate() { return new Contact(FirstName = 'Test', LastName = 'Contact', Email = 'test.contact@example.com'); } public Map templates() { return new Map{ 'business' => new Contact(FirstName = 'Business', LastName = 'Contact', Email = 'business.contact@example.com'), 'personal' => new Contact(FirstName = 'Personal', LastName = 'Contact', Email = 'personal.contact@example.com') }; } } public class ContactRandomizer implements TestModule.RecordRandomizer { public Map randomizers() { return new Map{ Contact.FirstName => new FirstNameRandomizer(), Contact.LastName => new LastNameRandomizer() }; } } public class FirstNameRandomizer implements TestModule.FieldRandomizer { private List firstNames = new List{ 'John', 'Jane', 'Bob', 'Alice' }; public Object generate(Integer index) { return firstNames[Math.mod(index, firstNames.size())]; } } public class LastNameRandomizer implements TestModule.FieldRandomizer { public Object generate(Integer index) { return 'Contact ' + (index + 1); } } } ``` -------------------------------- ### Implement Custom FieldRandomizer (IndustryRandomizer) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md This example demonstrates how to implement a custom FieldRandomizer. The `IndustryRandomizer` generates industry values by cycling through a predefined list of industries. ```apex public class IndustryRandomizer implements TestModule.FieldRandomizer { private List industries = new List randomizers() { return new Map{ Account.Name => new CompanyNameRandomizer(), Account.Industry => new IndustryRandomizer() }; } } public class CompanyNameRandomizer implements TestModule.FieldRandomizer { public Object generate(Integer index) { return 'Company ' + (index + 1); } } ``` -------------------------------- ### RecordRandomizer Implementation - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/randomizers.md Shows an example implementation of the RecordRandomizer interface, which defines randomizers for multiple fields within a record. This example randomizes both the Name and Industry fields of an Account. ```Apex public class AccountRandomizer implements TestModule.RecordRandomizer { public Map randomizers() { return new Map{ Account.Name => new CompanyNameRandomizer(), Account.Industry => new IndustryRandomizer() }; } } ``` -------------------------------- ### ListRandomizer Example - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/randomizers.md Demonstrates the use of the built-in ListRandomizer, which cycles through a provided list of values for a specific field. This is useful for testing scenarios with predefined, repeating data patterns. ```Apex List accounts = AccountTestModule.Mocker() .withRandomizer(Account.Industry, TestModule.ListRandomizer(new List{ 'A', 'B', 'C' })) .build(6); // Industries: A, B, C, A, B, C Assert.areEqual('A', accounts[0].get('Industry')); Assert.areEqual('B', accounts[1].get('Industry')); Assert.areEqual('C', accounts[2].get('Industry')); Assert.areEqual('A', accounts[3].get('Industry')); ``` -------------------------------- ### Apex Builder Pattern for Account Record Creation Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt Demonstrates creating a custom Apex builder for the Account SObject using Test Lib's RecordBuilder. It shows how to define type-safe methods for setting fields and provides examples for building single records, building and inserting single records, building multiple records, and building and inserting multiple records. ```apex public class AccountBuilder extends TestModule.RecordBuilder { public AccountBuilder() { super(new Account(Name = 'Test Account', Industry = 'Technology')); } public AccountBuilder withName(String name) { super.set(Account.Name, name); return this; } public AccountBuilder withIndustry(String industry) { super.set(Account.Industry, industry); return this; } public AccountBuilder withAnnualRevenue(Decimal revenue) { super.set(Account.AnnualRevenue, revenue); return this; } } @IsTest static void testAccountCreation() { Account acc = (Account) AccountTestModule.Builder() .withName('Acme Corp') .withIndustry('Technology') .build(); Assert.areEqual('Acme Corp', acc.Name); Assert.isNull(acc.Id); Account insertedAcc = (Account) AccountTestModule.Builder() .withName('Test Company') .withAnnualRevenue(500000) .buildAndInsert(); Assert.isNotNull(insertedAcc.Id); List accounts = AccountTestModule.Builder() .withIndustry('Finance') .build(5); Assert.areEqual(5, accounts.size()); List insertedAccounts = AccountTestModule.Builder() .withIndustry('Healthcare') .buildAndInsert(10); Assert.areEqual(10, insertedAccounts.size()); Assert.isNotNull(insertedAccounts[0].Id); } ``` -------------------------------- ### Test Trigger Context with Mock Maps and Fake IDs Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Provides an example of how to set up mock `oldMap` and `newMap` for testing trigger context using fake IDs. This technique is essential for unit testing Apex triggers, allowing you to simulate trigger events with fabricated data. ```apex Map oldMap = new Map(); Map newMap = new Map(); Id accId = TestModule.fakeId(Account.SObjectType); oldMap.put(accId, new Account(Id = accId, Rating = 'Cold')); newMap.put(accId, new Account(Id = accId, Rating = 'Hot')); // Test trigger handler with mock context AccountTriggerHandler.handleUpdate(oldMap, newMap); ``` -------------------------------- ### FieldRandomizer Implementation - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/randomizers.md Provides an example implementation of the FieldRandomizer interface for custom randomization logic. This class generates values by cycling through a predefined list of industries. ```Apex public class IndustryRandomizer implements TestModule.FieldRandomizer { private List industries = new List{ 'Technology', 'Finance', 'Healthcare', 'Retail' }; public Object generate(Integer index) { return industries[Math.mod(index, industries.size())]; } } ``` -------------------------------- ### Use ListRandomizer for Field Values Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md The ListRandomizer is a built-in randomizer that cycles through a provided list of values. This example shows how to use it to set the 'Industry' field for a list of accounts. ```apex List accounts = AccountTestModule.Builder() .withRandomizer(Account.Industry, TestModule.ListRandomizer(new List{ 'Tech', 'Finance', 'Health' })) .build(6); // Industries: Tech, Finance, Health, Tech, Finance, Health ``` -------------------------------- ### Build Multiple Mock Records (Apex) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Demonstrates building multiple mock records using both traditional Apex and the Test Lib Mocker. The Test Lib Mocker allows for more concise creation and setting of field values. ```apex List accounts = new List(); for (Integer i = 0; i < 10; i++) { accounts.add(new Account(Name = 'Account ' + i)); } ``` ```apex List accounts = AccountTestModule.Mocker() .set(Account.Industry, 'Technology') .build(10); ``` -------------------------------- ### Applying Named Templates with Test Lib (Apex) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/templates.md Demonstrates how to use the `useTemplate` method from the Test Lib to apply predefined 'enterprise' and 'startup' account templates. ```apex Account enterprise = (Account) AccountTestModule.Builder() .enterprise() .buildAndInsert(); Account startup = (Account) AccountTestModule.Builder() .startup() .buildAndInsert(); ``` -------------------------------- ### Combining Templates with Field Overrides (Apex) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/templates.md Illustrates how to apply a template and then override specific fields, such as the 'Name' field, for a more customized record creation. ```apex Account acc = (Account) AccountTestModule.Builder() .enterprise() .withName('Custom Enterprise Name') .buildAndInsert(); // Name: 'Custom Enterprise Name' // AnnualRevenue: 1000000 (from template) ``` -------------------------------- ### Build Multiple Mock Records Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md The `build` method allows you to create multiple mock records of a specified SObject type. This is useful for populating test data efficiently. ```APIDOC ## POST /build ### Description Builds multiple mock records for a given SObject type. ### Method POST ### Endpoint /build ### Parameters #### Query Parameters - **amount** (Integer) - Required - The number of mock records to build. ### Request Body ```json { "sobject_type": "Account", "fields": { "Industry": "Technology" } } ``` ### Response #### Success Response (200) - **records** (List) - A list of built mock SObject records. #### Response Example ```json { "records": [ { "attributes": {"type": "Account"}, "Industry": "Technology" }, { "attributes": {"type": "Account"}, "Industry": "Technology" } ] } ``` ``` -------------------------------- ### Custom Account Builder with Templates (Apex) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/templates.md Shows how to create a custom `AccountBuilder` that extends `TestModule.RecordBuilder` and utilizes the `Templates` class to provide specific account templates. ```apex public class AccountBuilder extends TestModule.RecordBuilder { public AccountBuilder() { super(new Templates()); } public AccountBuilder enterprise() { super.useTemplate('enterprise'); return this; } public AccountBuilder startup() { super.useTemplate('startup'); return this; } } ``` -------------------------------- ### Create Custom Builder with Convenience Methods Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Demonstrates how to create a custom Builder class that extends TestModule.RecordBuilder and adds convenience methods for setting common fields. This enhances code readability and maintainability. ```Apex public class AccountBuilder extends TestModule.RecordBuilder { public AccountBuilder() { super(new Account(Name = 'Test Account')); } public AccountBuilder withName(String name) { super.set(Account.Name, name); return this; } public AccountBuilder withIndustry(String industry) { super.set(Account.Industry, industry); return this; } } ``` -------------------------------- ### Build and Insert Multiple Records Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Builds and inserts a specified number of SObject records into the database. This method is ideal for populating the database with multiple records for comprehensive testing scenarios. ```Apex List accounts = AccountTestModule.Builder() .withIndustry('Technology') .buildAndInsert(10); ``` -------------------------------- ### Apply RecordRandomizer for Multiple Fields Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md This section demonstrates how to apply a RecordRandomizer to generate values for multiple fields when creating records. It contrasts the traditional Apex approach with the more concise Test Lib approach. ```apex // Traditional Apex List accounts = new List(); List industries = new List{'Technology', 'Finance', 'Healthcare'}; for (Integer i = 0; i < 100; i++) { accounts.add(new Account( Name = 'Company ' + (i + 1), Industry = industries[Math.mod(i, industries.size())] )); } insert accounts; ``` ```apex // Test Lib List accounts = AccountTestModule.Builder() .withAccountRandomizer() .buildAndInsert(100); ``` -------------------------------- ### Apex Test Data Creation with Test Lib Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/introduction.md Demonstrates creating both real database records using the builder pattern and in-memory records using the mocker pattern with Test Lib. The builder pattern involves DML operations, while the mocker pattern creates records without DML. ```apex // Builder - creates real records in database Account acc = (Account) AccountTestModule.Builder() .enterprise() .buildAndInsert(); // Mocker - creates in-memory records (no DML) Contact con = (Contact) ContactTestModule.Mocker() .setFakeId() .set('Account.Name', acc.Name) .build(); ``` -------------------------------- ### Apex Builder set() Methods for Field Assignment Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt Illustrates how to set field values on SObjects using Test Lib's Builder pattern. It shows the recommended approach using compile-time safe SObjectField tokens and also demonstrates using string field names, including a mixed approach. ```apex Account acc = (Account) AccountTestModule.Builder() .set(Account.Name, 'Acme Corp') .set(Account.Industry, 'Technology') .set(Account.AnnualRevenue, 1000000) .set(Account.NumberOfEmployees, 500) .buildAndInsert(); Account acc2 = (Account) AccountTestModule.Builder() .set('Name', 'Beta Corp') .set('Industry', 'Finance') .set('Website', 'https://beta.com') .build(); Contact con = (Contact) ContactTestModule.Builder() .set(Contact.FirstName, 'John') .set(Contact.LastName, 'Doe') .set('Email', 'john.doe@example.com') .buildAndInsert(); ``` -------------------------------- ### Build and Insert Single Record Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Builds a single SObject record and inserts it into the database. This method is suitable for integration tests where records need to exist with real IDs. ```Apex Account acc = (Account) AccountTestModule.Builder() .withName('Test Account') .withIndustry('Technology') .buildAndInsert(); ``` -------------------------------- ### Build Single Mock Record - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Builds a single mock SObject record after all fields and relationships have been set using the Mocker methods. This method performs no database operations, making it ideal for unit tests. It returns the constructed SObject instance. ```apex Account acc = (Account) AccountTestModule.Mocker() .set(Account.Name, 'Test Account') .set(Account.Industry, 'Technology') .build(); // No database operation - perfect for unit tests ``` -------------------------------- ### Build Single Record (No DML) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Builds a single SObject record without performing any database insertion (DML operation). This is useful for creating records for in-memory operations or further manipulation. ```Apex Account acc = (Account) AccountTestModule.Builder() .withName('Test Account') .withIndustry('Technology') .build(); ``` -------------------------------- ### Mocker API Usage Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md The Mocker API is designed for scenarios where you need to mock query results, test pure business logic without database interaction, or set read-only fields. ```APIDOC ## Mocker API ### Description The Mocker API provides a way to create mock SObjects for testing purposes. It is particularly useful for testing business logic, mocking query results with relationships, and setting read-only fields without performing DML operations. ### When to Use Mocker - Testing pure business logic without database interaction. - Testing calculations and transformations. - Mocking query results with relationships. - Achieving faster test execution by avoiding DML overhead. - Setting read-only fields (e.g., `CreatedDate`, formula fields). ### Example: Testing Business Logic ```apex @IsTest static void testDiscountCalculation() { Account acc = (Account) AccountTestModule.Mocker() .set(Account.AnnualRevenue, 500000) .set(Account.Type, 'Customer') .build(); Decimal discount = PricingService.calculateDiscount(acc); Assert.areEqual(0.15, discount); } ``` ### Key Feature: Setting Read-Only Fields Mocker creates records using JSON serialization, which allows setting read-only fields that are normally impossible to set directly in Apex. ``` -------------------------------- ### Build Multiple Records (No DML) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Builds a specified number of SObject records without inserting them into the database. This is efficient for generating test data sets for in-memory processing. ```Apex List accounts = AccountTestModule.Builder() .withIndustry('Technology') .build(10); ``` -------------------------------- ### Create Mock Records Manually with Fake IDs Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Shows how to create mock Salesforce records manually by assigning a fake ID generated by `TestModule.fakeId()`. This is a common use case for setting up test data when you need to instantiate objects with valid-looking IDs without database interaction. ```apex Account acc = new Account( Id = TestModule.fakeId(Account.SObjectType), Name = 'Test Account' ); ``` -------------------------------- ### Define and Use Apex Test Templates Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt Demonstrates how to define reusable record configurations using the Templates class and apply them with a RecordBuilder. Supports default templates, named templates, and template overrides. ```apex public class Templates implements TestModule.Template { public SObject defaultTemplate() { return new Account( Name = 'Test Account', Industry = 'Technology' ); } public Map templates() { return new Map{ 'enterprise' => new Account( Name = 'Enterprise Account', Industry = 'Technology', AnnualRevenue = 1000000, NumberOfEmployees = 500 ), 'startup' => new Account( Name = 'Startup Account', Industry = 'Technology', AnnualRevenue = 100000, NumberOfEmployees = 10 ), 'nonprofit' => new Account( Name = 'Nonprofit Org', Industry = 'Not For Profit', AnnualRevenue = 50000 ) }; } } public class AccountBuilder extends TestModule.RecordBuilder { public AccountBuilder() { super(new Templates()); } public AccountBuilder enterprise() { super.useTemplate('enterprise'); return this; } public AccountBuilder startup() { super.useTemplate('startup'); return this; } public AccountBuilder nonprofit() { super.useTemplate('nonprofit'); return this; } } @IsTest static void testTemplates() { Account enterprise = (Account) AccountTestModule.Builder() .enterprise() .buildAndInsert(); Assert.areEqual('Enterprise Account', enterprise.Name); Assert.areEqual(1000000, enterprise.AnnualRevenue); Account customEnterprise = (Account) AccountTestModule.Builder() .enterprise() .withName('Custom Enterprise') .buildAndInsert(); Assert.areEqual('Custom Enterprise', customEnterprise.Name); Assert.areEqual(1000000, customEnterprise.AnnualRevenue); } ``` -------------------------------- ### Generate Fake IDs with Correct Key Prefixes Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Illustrates the generation of fake IDs with their correct key prefixes for different SObject types. This ensures that the generated IDs are structurally valid Salesforce IDs, which is important for simulating real data in tests. ```apex Id accountId = TestModule.IdGenerator.get(Account.SObjectType); // 001... Id contactId = TestModule.IdGenerator.get(Contact.SObjectType); // 003... Id oppId = TestModule.IdGenerator.get(Opportunity.SObjectType); // 006... Id leadId = TestModule.IdGenerator.get(Lead.SObjectType); // 00Q... ``` -------------------------------- ### Cycle Through List Values with ListRandomizer (Apex) Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The ListRandomizer utility provides a quick way to randomize data by cycling through a provided list of values. This is useful for fields where a specific set of values should be used in rotation. It can be applied directly to fields using the `withRandomizer` method. ```apex @IsTest static void testListRandomizer() { List accounts = AccountTestModule.Builder() .withRandomizer( Account.Industry, TestModule.ListRandomizer(new List{ 'Tech', 'Finance', 'Health' }) ) .withRandomizer( Account.Rating, TestModule.ListRandomizer(new List{ 'Hot', 'Warm', 'Cold' }) ) .build(9); Assert.areEqual('Tech', accounts[0].get('Industry')); Assert.areEqual('Finance', accounts[1].get('Industry')); Assert.areEqual('Health', accounts[2].get('Industry')); Assert.areEqual('Tech', accounts[3].get('Industry')); Assert.areEqual('Hot', accounts[0].get('Rating')); Assert.areEqual('Warm', accounts[1].get('Rating')); Assert.areEqual('Cold', accounts[2].get('Rating')); } ``` -------------------------------- ### Implement Apex FieldRandomizer Interface Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt Shows how to implement the FieldRandomizer interface to generate unique or patterned values for specific fields when creating multiple records. This is useful for ensuring data diversity in tests. ```apex public class IndustryRandomizer implements TestModule.FieldRandomizer { private List industries = new List{ 'Technology', 'Finance', 'Healthcare', 'Retail', 'Manufacturing' }; public Object generate(Integer index) { return industries[Math.mod(index, industries.size())]; } } public class CompanyNameRandomizer implements TestModule.FieldRandomizer { public Object generate(Integer index) { return 'Company ' + (index + 1); } } public class EmailRandomizer implements TestModule.FieldRandomizer { public Object generate(Integer index) { return 'user' + (index + 1) + '@example.com'; } } @IsTest static void testFieldRandomizer() { List accounts = AccountTestModule.Builder() .withRandomizer(Account.Industry, new IndustryRandomizer()) .withRandomizer(Account.Name, new CompanyNameRandomizer()) .buildAndInsert(10); Assert.areEqual('Company 1', accounts[0].get('Name')); Assert.areEqual('Technology', accounts[0].get('Industry')); Assert.areEqual('Company 2', accounts[1].get('Name')); Assert.areEqual('Finance', accounts[1].get('Industry')); } ``` -------------------------------- ### Implement RecordRandomizer for Grouped Field Randomization (Apex) Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The RecordRandomizer interface allows grouping multiple field randomizers for a single SObject type. This ensures consistent bulk record generation by applying all randomizers simultaneously. It requires implementing the `randomizers` method to return a map of SObjectField to FieldRandomizer. ```apex public class AccountRandomizer implements TestModule.RecordRandomizer { public Map randomizers() { return new Map{ Account.Name => new CompanyNameRandomizer(), Account.Industry => new IndustryRandomizer(), Account.AnnualRevenue => new RevenueRandomizer() }; } } public class RevenueRandomizer implements TestModule.FieldRandomizer { private List revenues = new List{ 100000, 500000, 1000000, 5000000 }; public Object generate(Integer index) { return revenues[Math.mod(index, revenues.size())]; } } public class AccountBuilder extends TestModule.RecordBuilder { public AccountBuilder withAccountRandomizer() { super.withRandomizer(new AccountRandomizer()); return this; } } @IsTest static void testRecordRandomizer() { List accounts = AccountTestModule.Builder() .withAccountRandomizer() .buildAndInsert(100); Assert.areEqual('Company 1', accounts[0].get('Name')); Assert.areEqual('Company 100', accounts[99].get('Name')); Assert.areEqual(100, accounts.size()); } ``` -------------------------------- ### Test with Maps Using Fake IDs Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Demonstrates the use of fake IDs when working with Maps in Apex tests. A fake ID can be generated and used as a key in a Map, allowing you to test map-related logic without relying on actual database records. ```apex Id fakeId = TestModule.fakeId(Account.SObjectType); Map accountNames = new Map{ fakeId => 'Test' }; Assert.isTrue(accountNames.containsKey(fakeId)); ``` -------------------------------- ### Set Field Value using SObjectField Token Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Sets a field value on an SObject record using an SObjectField token, providing compile-time validation. This method is part of the Test Lib Builder and returns the builder instance for chaining. ```Apex Account acc = (Account) AccountTestModule.Builder() .set(Account.Name, 'Acme Corp') .set(Account.Industry, 'Technology') .set(Account.AnnualRevenue, 1000000) .build(); ``` -------------------------------- ### Template Interface Definition (Apex) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/templates.md Defines the contract for template implementations, requiring methods for a default template and a map of named templates. ```apex public interface Template { SObject defaultTemplate(); Map templates(); } ``` -------------------------------- ### Apply FieldRandomizer for a Single Field Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md This code snippet shows how to apply a FieldRandomizer to a specific field using the `withRandomizer` method in Test Lib. It's useful for generating values for a single field across multiple records. ```apex List accounts = AccountTestModule.Builder() .withRandomizer(Account.Industry, new IndustryRandomizer()) .buildAndInsert(10); ``` -------------------------------- ### Set Field Value using String Field Name Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/build.md Sets a field value on an SObject record using a string field name. This method is useful when SObjectField tokens are not available or preferred. It returns the builder instance for chaining. ```Apex Account acc = (Account) AccountTestModule.Builder() .set('Name', 'Acme Corp') .set('Industry', 'Technology') .build(); ``` -------------------------------- ### Apex RecordMocker: Create and Configure In-Memory SObjects Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The RecordMocker abstract class in Apex facilitates the creation of in-memory SObject records. It supports setting field values, mocking parent relationships using dot notation, and assigning fake IDs for testing scenarios without database interaction. ```apex public class ContactMocker extends TestModule.RecordMocker { public ContactMocker() { super(new Contact(FirstName = 'Test', LastName = 'Contact')); } public ContactMocker withFirstName(String firstName) { super.set(Contact.FirstName, firstName); return this; } public ContactMocker withLastName(String lastName) { super.set(Contact.LastName, lastName); return this; } public ContactMocker withAccountName(String accountName) { super.set('Account.Name', accountName); return this; } public ContactMocker withFakeId() { super.setFakeId(); return this; } } // Usage in test class @IsTest static void testMockerUsage() { // Build single mock record Contact con = (Contact) ContactTestModule.Mocker() .withFirstName('Jane') .withLastName('Smith') .withFakeId() .build(); Assert.areEqual('Jane', con.FirstName); Assert.isNotNull(con.Id); // Fake ID assigned // Mock parent relationship using dot notation Contact conWithParent = (Contact) ContactTestModule.Mocker() .set(Contact.FirstName, 'Bob') .set('Account.Name', 'Parent Company') .set('Account.Industry', 'Technology') .build(); Assert.areEqual('Parent Company', conWithParent.Account.Name); // Mock deeply nested relationships Contact deepNested = (Contact) ContactTestModule.Mocker() .set('Account.Parent.Name', 'Grandparent Corp') .build(); Assert.areEqual('Grandparent Corp', deepNested.Account.Parent.Name); // Build multiple mock records List contacts = ContactTestModule.Mocker() .set(Contact.Email, 'test@example.com') .build(10); Assert.areEqual(10, contacts.size()); } ``` -------------------------------- ### Generate Fake ID (Convenience Method) Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md A convenience static method for generating fake Salesforce IDs. Similar to `IdGenerator.get()`, this method provides a quick way to obtain a fake ID for an SObject type, primarily used when manually creating records or populating maps for testing. ```apex Id fakeId = TestModule.fakeId(Account.SObjectType); Assert.isTrue(String.valueOf(fakeId).startsWith('001')); ``` -------------------------------- ### Set Field Value using SObjectField Token - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Sets a field value on a mock SObject using the SObjectField token. This method is part of the Mocker class and is used to define the properties of the mock record before building it. It takes an SObjectField and the desired value as input. ```apex Account acc = (Account) AccountTestModule.Mocker() .set(Account.Name, 'Mock Account') .set(Account.Industry, 'Technology') .build(); ``` -------------------------------- ### Generate Fake Salesforce IDs with IdGenerator (Apex) Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The IdGenerator utility creates valid-looking Salesforce IDs without requiring database operations. This is beneficial for scenarios where fake IDs are needed outside of the Mocker pattern, such as in trigger testing or manual record creation. It supports generating IDs for any SObject type and ensures correct key prefixes. ```apex @IsTest static void testIdGenerator() { Id accountId = TestModule.IdGenerator.get(Account.SObjectType); Id contactId = TestModule.IdGenerator.get(Contact.SObjectType); Id oppId = TestModule.IdGenerator.get(Opportunity.SObjectType); Assert.isTrue(String.valueOf(accountId).startsWith('001')); Assert.isTrue(String.valueOf(contactId).startsWith('003')); Assert.isTrue(String.valueOf(oppId).startsWith('006')); Id fakeId = TestModule.fakeId(Account.SObjectType); Assert.isNotNull(fakeId); Id id1 = TestModule.IdGenerator.get(Account.SObjectType); Id id2 = TestModule.IdGenerator.get(Account.SObjectType); Id id3 = TestModule.IdGenerator.get(Account.SObjectType); Assert.areNotEqual(id1, id2); Assert.areNotEqual(id2, id3); Account acc = new Account( Id = TestModule.fakeId(Account.SObjectType), Name = 'Test Account' ); Map oldMap = new Map(); Map newMap = new Map(); Id accId = TestModule.fakeId(Account.SObjectType); oldMap.put(accId, new Account(Id = accId, Rating = 'Cold')); newMap.put(accId, new Account(Id = accId, Rating = 'Hot')); } ``` -------------------------------- ### Apex RecordMocker: Generating Fake IDs with setFakeId() Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The `setFakeId()` method generates valid-looking Salesforce IDs for SObjects without performing any database insertions. This is particularly useful when testing code that expects records to have IDs, such as in map operations or when referencing related records. ```apex @IsTest static void testFakeIds() { // Generate fake ID via Mocker Account acc1 = (Account) AccountTestModule.Mocker() .setFakeId() .build(); Account acc2 = (Account) AccountTestModule.Mocker() .setFakeId() .build(); // Each call generates unique ID Assert.isNotNull(acc1.Id); Assert.isNotNull(acc2.Id); Assert.areNotEqual(acc1.Id, acc2.Id); // IDs use correct key prefix for SObject type Assert.isTrue(String.valueOf(acc1.Id).startsWith('001')); // Account prefix Contact con = (Contact) ContactTestModule.Mocker() .setFakeId() .build(); Assert.isTrue(String.valueOf(con.Id).startsWith('003')); // Contact prefix // Use in Map operations Map accountMap = new Map(); accountMap.put(acc1.Id, acc1); accountMap.put(acc2.Id, acc2); Assert.isTrue(accountMap.containsKey(acc1.Id)); } ``` -------------------------------- ### Generate Unique and Incrementing Fake IDs Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Demonstrates that each call to `IdGenerator.get()` produces a unique and incrementing ID. This is crucial for tests that require distinct identifiers for multiple records, ensuring that comparisons and lookups work correctly. ```apex Id id1 = TestModule.IdGenerator.get(Account.SObjectType); Id id2 = TestModule.IdGenerator.get(Account.SObjectType); Id id3 = TestModule.IdGenerator.get(Account.SObjectType); Assert.areNotEqual(id1, id2); Assert.areNotEqual(id2, id3); Assert.areNotEqual(id1, id3); ``` -------------------------------- ### Define FieldRandomizer Interface Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md The FieldRandomizer interface defines a single method `generate` which takes an integer index and returns an Object representing the generated field value. This is used for generating values for individual fields. ```apex public interface FieldRandomizer { Object generate(Integer index); } ``` -------------------------------- ### Generate Fake Salesforce ID for SObject Type Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/utilities/id-generator.md Generates a fake Salesforce ID for a specified SObject type. This method is useful for creating mock records or setting up test data without performing actual database operations. It ensures the generated ID has the correct key prefix for the given SObject. ```apex Id accountId = TestModule.IdGenerator.get(Account.SObjectType); Id contactId = TestModule.IdGenerator.get(Contact.SObjectType); Assert.isTrue(String.valueOf(accountId).startsWith('001')); Assert.isTrue(String.valueOf(contactId).startsWith('003')); ``` -------------------------------- ### Generate and Set Fake ID - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Generates and sets a fake ID for the mock SObject record. This is useful when testing code that requires a record ID but does not need an actual database record, such as in map operations or trigger handlers. Each call generates a unique ID. ```apex Account acc = (Account) AccountTestModule.Mocker() .setFakeId() .build(); // acc.Id is a valid-looking ID like 001000000000001 Assert.isNotNull(acc.Id); Assert.isTrue(String.valueOf(acc.Id).startsWith('001')); ``` ```apex Account acc1 = (Account) AccountTestModule.Mocker().setFakeId().build(); Account acc2 = (Account) AccountTestModule.Mocker().setFakeId().build(); Assert.areNotEqual(acc1.Id, acc2.Id); ``` -------------------------------- ### Apex Test Module for Contact SObject Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt This Apex code defines a complete TestModule for the Contact SObject, providing both Builder and Mocker capabilities. It includes nested classes for record building, mocking, templates, and randomizers, adhering to the TestModule pattern for Salesforce testing. ```apex @IsTest public class ContactTestModule implements TestModule.BuilderProvider, TestModule.MockerProvider { // Static factory methods public static ContactBuilder Builder() { return new ContactBuilder(); } public static ContactMocker Mocker() { return new ContactMocker(); } // Builder class public class ContactBuilder extends TestModule.RecordBuilder { public ContactBuilder() { super(new Templates()); } public ContactBuilder withFirstName(String firstName) { super.set(Contact.FirstName, firstName); return this; } public ContactBuilder withLastName(String lastName) { super.set(Contact.LastName, lastName); return this; } public ContactBuilder withEmail(String email) { super.set(Contact.Email, email); return this; } public ContactBuilder business() { super.useTemplate('business'); return this; } public ContactBuilder personal() { super.useTemplate('personal'); return this; } public ContactBuilder withContactRandomizer() { super.withRandomizer(new ContactRandomizer()); return this; } } // Mocker class public class ContactMocker extends TestModule.RecordMocker { public ContactMocker() { super(new Contact(FirstName = 'Test', LastName = 'Contact')); } public ContactMocker withFirstName(String firstName) { super.set(Contact.FirstName, firstName); return this; } public ContactMocker withLastName(String lastName) { super.set(Contact.LastName, lastName); return this; } public ContactMocker withAccountName(String accountName) { super.set('Account.Name', accountName); return this; } public ContactMocker withFakeId() { super.setFakeId(); return this; } } // Templates public class Templates implements TestModule.Template { public SObject defaultTemplate() { return new Contact(FirstName = 'Test', LastName = 'Contact', Email = 'test@example.com'); } public Map templates() { return new Map{ 'business' => new Contact(FirstName = 'Business', LastName = 'Contact', Email = 'business@example.com'), 'personal' => new Contact(FirstName = 'Personal', LastName = 'Contact', Email = 'personal@example.com') }; } } // Randomizers public class ContactRandomizer implements TestModule.RecordRandomizer { public Map randomizers() { return new Map{ Contact.FirstName => new FirstNameRandomizer(), Contact.LastName => new LastNameRandomizer() }; } } public class FirstNameRandomizer implements TestModule.FieldRandomizer { private List names = new List{ 'John', 'Jane', 'Bob', 'Alice' }; public Object generate(Integer index) { return names[Math.mod(index, names.size())]; } } public class LastNameRandomizer implements TestModule.FieldRandomizer { public Object generate(Integer index) { return 'Contact ' + (index + 1); } } } ``` -------------------------------- ### Define RecordRandomizer Interface Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/builder/randomizers.md The RecordRandomizer interface defines a method `randomizers` that returns a map of SObjectField to FieldRandomizer. This allows for defining multiple field randomizers for a single record. ```apex public interface RecordRandomizer { Map randomizers(); } ``` -------------------------------- ### Apply Record Randomizer - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/randomizers.md Applies a randomizer that generates values for multiple fields within a record. This is useful for creating mock records with diverse and unique field data. ```Apex List accounts = AccountTestModule.Mocker() .withAccountRandomizer() .build(100); // Each account has unique Name and cycling Industry ``` -------------------------------- ### Set Field Value using String Name - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Sets a field value on a mock SObject using a string field name. This method supports dot notation for accessing parent relationship fields and deeply nested fields. It's useful for mocking complex object structures without direct SObjectField tokens. ```apex Account acc = (Account) AccountTestModule.Mocker() .set('Name', 'Mock Account') .set('Industry', 'Technology') .build(); ``` ```apex Account acc = (Account) AccountTestModule.Mocker() .set('Parent.Name', 'Parent Corporation') .build(); // acc.Parent.Name == 'Parent Corporation' ``` ```apex Contact con = (Contact) ContactTestModule.Mocker() .set('Account.Parent.Name', 'Grandparent Corp') .build(); // con.Account.Parent.Name == 'Grandparent Corp' ``` ```apex Account acc = (Account) AccountTestModule.Mocker() .setFakeId() .set('CreatedDate', Datetime.newInstance(2025, 1, 15, 10, 30, 0)) .set('Owner.Name', 'System Admin') .build(); Assert.areEqual('System Admin', acc.Owner.Name); ``` -------------------------------- ### Set Child Relationship Records - Apex Source: https://github.com/beyond-the-cloud-dev/test-lib/blob/main/website/mocker/build.md Sets child relationship records for a mock parent SObject. This method allows you to populate related lists, such as Contacts on an Account, without performing database queries. It takes the relationship API name and a list of child SObjects. ```apex List contacts = (List) ContactTestModule.Mocker() .build(3); Account acc = (Account) AccountTestModule.Mocker() .setChildren('Contacts', contacts) .build(); // acc.Contacts.size() == 3 ``` ```apex List contacts = (List) ContactTestModule.Mocker().build(5); List opportunities = (List) OpportunityTestModule.Mocker().build(3); Account acc = (Account) AccountTestModule.Mocker() .setFakeId() .setChildren('Contacts', contacts) .setChildren('Opportunities', opportunities) .build(); Assert.areEqual(5, acc.Contacts.size()); Assert.areEqual(3, acc.Opportunities.size()); ``` -------------------------------- ### Apex RecordMocker: Mocking Child Relationships with setChildren() Source: https://context7.com/beyond-the-cloud-dev/test-lib/llms.txt The `setChildren()` method of the RecordMocker allows for mocking child relationship collections on parent records. This is crucial for testing code that utilizes SOQL subqueries without requiring database operations. ```apex @IsTest static void testChildRelationships() { // Create mock child contacts List mockContacts = new List(); for (Integer i = 0; i < 5; i++) { mockContacts.add((Contact) ContactTestModule.Mocker() .withFirstName('Contact') .withLastName('Person ' + i) .withFakeId() .build()); } // Create mock opportunities List mockOpps = new List(); for (Integer i = 0; i < 3; i++) { mockOpps.add((Opportunity) OpportunityTestModule.Mocker() .set(Opportunity.Name, 'Deal ' + i) .set(Opportunity.Amount, 50000 * (i + 1)) .build()); } // Create account with child relationships Account acc = (Account) AccountTestModule.Mocker() .set(Account.Name, 'Parent Account') .setFakeId() .setChildren('Contacts', mockContacts) .setChildren('Opportunities', mockOpps) .build(); // Access children as if queried from database Assert.areEqual(5, acc.Contacts.size()); Assert.areEqual(3, acc.Opportunities.size()); Assert.areEqual('Contact', acc.Contacts[0].FirstName); Assert.areEqual('Deal 0', acc.Opportunities[0].Name); } ```