Skip to content

TST_Factory

Class · Group: Testing

apex
global without sharing class TST_Factory

Factory class for generating test data, permission set assignments, share records, metadata updates, and failure logs across Salesforce objects. Optimized for unit tests and integration processes, providing methods to create records with random data and configure system settings such as API toggles, triggers, and scheduled jobs.

Example

apex
User testUser = TST_Factory.newUser('Standard User');
insert testUser;

Methods

MethodDescription
global static void createPermissionSetAssignments(List<User> users, Id permissionSetOrGroupId)Creates PermissionSetAssignment records for a list of users and a permission set Id.
global static void createPermissionSetAssignments(List<User> users, String permissionSetOrGroupName)Creates PermissionSetAssignment records for a list of users and a permission set.
global static ApiCall__c newApiCall()Creates an uncommitted ApiCall__c record for a web service call.
global static ApiCall__c newApiCall(String serviceName)Creates an uncommitted ApiCall__c record with a specified service name.
global static ContentVersion newContentVersion(Id linkToObjectId, String fileName, Blob body)Creates an uncommitted ContentVersion record from file data.
global static FeatureFlag__mdt newFeatureFlag(String flagName)Activates a feature flag for testing by injecting it into the selector cache.
global static ApiCall__c newInboundApiCall(String serviceName)Creates an uncommitted ApiCall__c record for an inbound web service call.
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath)Creates a mock inbound ApiSetting__mdt record via TST_Mock for test routing.
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath, Integer priority)Creates a mock inbound ApiSetting__mdt record with a custom priority, registered with TST_Mock for query interception.
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath, Integer priority, Map<SObjectField, Object> overrides)Creates a mock inbound ApiSetting__mdt record with a custom priority and additional field overrides, registered with TST_Mock for query interception.
global static ApiCall__c newOutboundApiCall(String serviceName)Creates an uncommitted ApiCall__c record for an outbound web service call.
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId)Creates an uncommitted ApiCall__c record for an outbound web service call with a triggering object.
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId, Map<String, String> requestParameters)Creates an uncommitted ApiCall__c record for an outbound web service call with parameters.
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId, String parameterName, String parameterValue)Creates an uncommitted ApiCall__c record for an outbound web service call with a single parameter.
global static ApiSetting__mdt newOutboundApiSetting(String className, Map<SObjectField, Object> overrides)Creates a mock outbound ApiSetting__mdt record via TST_Mock for query interception.
global static User newUser(String profileName)Creates a single uncommitted User record with the specified profile.
global static User newUser(String profileName, String companyName)Creates an uncommitted User record with a custom company name.
global static List<User> newUsers(String profileName, Integer numberOfUsers)Creates a list of uncommitted User records with the specified profile.
global static User newUserWithPermissionSet(String profileName, String companyName, String permissionSetName)Creates and inserts a User with the specified profile + company name, then assigns the named permission set (or permission set group).

createPermissionSetAssignments

apex
global static void createPermissionSetAssignments(List<User> users, Id permissionSetOrGroupId)

Creates PermissionSetAssignment records for a list of users and a permission set Id.

Parameters

ParameterTypeDescription
usersListThe list of users to assign the permission set to.
permissionSetOrGroupIdUserThe Id of the permission set.

Example

apex
List<User> users = TST_Factory.newUsers('Standard User', 2);
insert users;
PermissionSet permissionSet = [SELECT Id FROM PermissionSet WHERE Name = 'CustomPermissionSet' LIMIT 1];
TST_Factory.createPermissionSetAssignments(users, permissionSet.Id);
System.debug('Permission Set Assignments Created');
apex
global static void createPermissionSetAssignments(List<User> users, String permissionSetOrGroupName)

Creates PermissionSetAssignment records for a list of users and a permission set.

Parameters

ParameterTypeDescription
usersListThe list of users to assign the permission set to.
permissionSetOrGroupNameUserThe name of the permission set.

Throws

ExceptionDescription
AssertExceptionIf no permission set is found for the specified name.

Example

apex
List<User> users = TST_Factory.newUsers('Standard User', 2);
insert users;
TST_Factory.createPermissionSetAssignments(users, 'CustomPermissionSet');
System.debug('Permission Set Assignments Created');

newApiCall

apex
global static ApiCall__c newApiCall()

Creates an uncommitted ApiCall__c record for a web service call.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
ApiCall__c apiCall = TST_Factory.newApiCall();
insert apiCall;
System.debug('API Call Id: ' + apiCall.Id);
apex
global static ApiCall__c newApiCall(String serviceName)

Creates an uncommitted ApiCall__c record with a specified service name.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
ApiCall__c apiCall = TST_Factory.newApiCall('MyService');
insert apiCall;
System.debug('API Call Service: ' + apiCall.ServiceName__c);

newContentVersion

apex
global static ContentVersion newContentVersion(Id linkToObjectId, String fileName, Blob body)

Creates an uncommitted ContentVersion record from file data.

Parameters

ParameterTypeDescription
linkToObjectIdIdThe Id of the object to link the content version to.
fileNameStringThe name of the file.
bodyBlobThe binary data of the file.

Returns ContentVersion — An uncommitted ContentVersion record.

Example

apex
Account acc = TST_Factory.newAccount();
insert acc;
ContentVersion version = TST_Factory.newContentVersion(acc.Id, 'test.pdf', Blob.valueOf('Test data'));
insert version;
System.debug('ContentVersion Title: ' + version.Title);

newFeatureFlag

apex
global static FeatureFlag__mdt newFeatureFlag(String flagName)

Activates a feature flag for testing by injecting it into the selector cache. UTIL_FeatureFlag.isEnabled(flagName) will return true after this call.

Parameters

ParameterTypeDescription
flagNameStringThe developer name of the feature flag to activate.

Returns FeatureFlag__mdt — The activated FeatureFlag__mdt record.

Example

apex
TST_Factory.newFeatureFlag('MyFeatureFlag');

newInboundApiCall

apex
global static ApiCall__c newInboundApiCall(String serviceName)

Creates an uncommitted ApiCall__c record for an inbound web service call.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
ApiCall__c inboundApiCall = TST_Factory.newInboundApiCall('InboundService');
insert inboundApiCall;
System.debug('Inbound API Call Id: ' + inboundApiCall.Id);

newInboundApiSetting

apex
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath)

Creates a mock inbound ApiSetting__mdt record via TST_Mock for test routing. The setting is registered in the mock cache and will be returned by SEL_ApiSetting queries.

Parameters

ParameterTypeDescription
classNameStringThe fully qualified name of the inbound API handler class
endpointPathStringThe URL path pattern for routing (e.g., '/echo/*')

Returns ApiSetting__mdt — A mock ApiSetting__mdt record

Example

apex
ApiSetting__mdt setting = TST_Factory.newInboundApiSetting('API_Echo', '/echo/*');
apex
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath, Integer priority)

Creates a mock inbound ApiSetting__mdt record with a custom priority, registered with TST_Mock for query interception.

Parameters

ParameterTypeDescription
classNameStringThe API handler class name
endpointPathStringThe URL path pattern for routing (e.g., '/echo/*')
priorityIntegerThe routing priority (lower number wins when paths are equal)

Returns ApiSetting__mdt — A mock ApiSetting__mdt record

Example

apex
ApiSetting__mdt setting = TST_Factory.newInboundApiSetting('API_Echo', '/echo/*', 50);
apex
global static ApiSetting__mdt newInboundApiSetting(String className, String endpointPath, Integer priority, Map<SObjectField, Object> overrides)

Creates a mock inbound ApiSetting__mdt record with a custom priority and additional field overrides, registered with TST_Mock for query interception.

Parameters

ParameterTypeDescription
classNameStringThe API handler class name
endpointPathStringThe URL path pattern for routing (e.g., '/echo/*')
priorityIntegerThe routing priority (lower number wins when paths are equal)
overridesMapAdditional field values to apply on top of the defaults (may be null)

Returns ApiSetting__mdt — A mock ApiSetting__mdt record

Example

apex
ApiSetting__mdt setting = TST_Factory.newInboundApiSetting('API_Echo', '/echo/*', 100, new Map<SObjectField, Object>
{
    ApiSetting__mdt.MockingEnabled__c => true
});

newOutboundApiCall

apex
global static ApiCall__c newOutboundApiCall(String serviceName)

Creates an uncommitted ApiCall__c record for an outbound web service call.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
ApiCall__c outboundApiCall = TST_Factory.newOutboundApiCall('OutboundService');
insert outboundApiCall;
System.debug('Outbound API Call Id: ' + outboundApiCall.Id);
apex
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId)

Creates an uncommitted ApiCall__c record for an outbound web service call with a triggering object.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.
recordIdIdThe Id of the object triggering the service.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
Account acc = TST_Factory.newAccount();
insert acc;
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', acc.Id);
insert apiCall;
System.debug('API Call Id: ' + apiCall.Id);
apex
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId, Map<String, String> requestParameters)

Creates an uncommitted ApiCall__c record for an outbound web service call with parameters.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.
recordIdIdThe Id of the object triggering the service.
requestParametersMapA map of name-value pairs for request parameters.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
Account acc = TST_Factory.newAccount();
insert acc;
Map<String, String> params = new Map<String, String>
{
    'key' => 'value'
};
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', acc.Id, params);
insert apiCall;
System.debug('API Call Id: ' + apiCall.Id);
apex
global static ApiCall__c newOutboundApiCall(String serviceName, Id recordId, String parameterName, String parameterValue)

Creates an uncommitted ApiCall__c record for an outbound web service call with a single parameter.

Parameters

ParameterTypeDescription
serviceNameStringThe name of the web service class.
recordIdIdThe Id of the object triggering the service.
parameterNameStringThe name of the additional parameter.
parameterValueStringThe value of the additional parameter.

Returns ApiCall__c — An uncommitted ApiCall__c record.

Example

apex
Account acc = TST_Factory.newAccount();
insert acc;
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', acc.Id, 'key', 'value');
insert apiCall;
System.debug('API Call Id: ' + apiCall.Id);

newOutboundApiSetting

apex
global static ApiSetting__mdt newOutboundApiSetting(String className, Map<SObjectField, Object> overrides)

Creates a mock outbound ApiSetting__mdt record via TST_Mock for query interception. The setting defaults to active and Outbound direction; overrides can replace any field value including IsActive__c. Pass null when no overrides are needed.

Parameters

ParameterTypeDescription
classNameStringThe fully qualified name of the outbound API handler class
overridesMapAdditional field values to apply on top of the defaults (may be null)

Returns ApiSetting__mdt — A mock ApiSetting__mdt record

Example

apex
ApiSetting__mdt setting = TST_Factory.newOutboundApiSetting('API_SendEmail', null);

newUser

apex
global static User newUser(String profileName)

Creates a single uncommitted User record with the specified profile.

Parameters

ParameterTypeDescription
profileNameStringThe name of the profile to assign to the user.

Returns User — An uncommitted User record.

Example

apex
User testUser = TST_Factory.newUser('System Administrator');
insert testUser;
System.debug('User Email: ' + testUser.Email);
apex
global static User newUser(String profileName, String companyName)

Creates an uncommitted User record with a custom company name.

The company name can be used as a unique identifier to later retrieve this specific user

Parameters

ParameterTypeDescription
profileNameStringThe Profile name to assign to the user.
companyNameStringA unique company name for this user.

Returns User — An uncommitted User record with the specified company name.

Example

apex
@TestSetup
private static void setupTestData()
{
    User testUser = TST_Factory.newUser('Standard User', 'my-test-user');
    insert testUser;
}
private static User getTestUser()
{
    return new SEL_User().findByCompanyName('my-test-user');
}

newUsers

apex
global static List<User> newUsers(String profileName, Integer numberOfUsers)

Creates a list of uncommitted User records with the specified profile.

Parameters

ParameterTypeDescription
profileNameStringThe name of the profile to assign to the users.
numberOfUsersIntegerThe number of users to create.

Returns User — A list of uncommitted User records.

Example

apex
List<User> mockUsers = TST_Factory.newUsers('Standard User', 5);
insert mockUsers;
for (User u : mockUsers)
{
System.debug('User Email: ' + u.Email);
}

newUserWithPermissionSet

apex
global static User newUserWithPermissionSet(String profileName, String companyName, String permissionSetName)

Creates and inserts a User with the specified profile + company name, then assigns the named permission set (or permission set group). Composes newUser(profileName, companyName), insert, and createPermissionSetAssignments(List , String).

Intended for use in @TestSetup as a committed test admin that test methods reach via System.runAs. Because runAs re-evaluates permissions for the inner scope, the test admin receives a fresh permission cache — bypassing the stale-cache issue that affects mutation of the currently-running user's permission set mid-transaction (the failure mode that made assignAdministratorPermissionSet() unreliable in the 2GP synthetic validation org).

Parameters

ParameterTypeDescription
profileNameStringThe Profile name to assign to the user.
companyNameStringA unique company name for this user. Used as the retrieval discriminator via SEL_User.findByCompanyName.
permissionSetNameStringThe API name of the permission set (or permission set group) to assign.

Returns User — The committed User record with the permission set assigned.

Throws

ExceptionDescription
AssertExceptionIf the profile or permission set cannot be resolved for the target org.

Example

apex
private static final String TEST_ADMIN_COMPANY = 'MyClass_TEST-admin';
@TestSetup
private static void setupTestAdmin()
{
    TST_Factory.newUserWithPermissionSet(
            'System Administrator',
            TEST_ADMIN_COMPANY,
            SEL_PermissionSet.ADMIN_PERMISSION_SET_API_NAME
    );
}
private static User getTestAdmin()
{
    return new SEL_User().findByCompanyName(TEST_ADMIN_COMPANY);
}
@IsTest
private static void shouldDoX()
{
    System.runAs(getTestAdmin())
    {
        // test body
    }
}