Skip to content

TST_Factory ​

Class · Group: Testing

Learn it: Fast Start - Test Data and Test Data guide

apex
global without sharing class TST_Factory

Factory class that builds test data for your unit tests. It has helpers for: users (new or inserted, with or without a permission set), permission set assignments, feature flag records, API call records (inbound and outbound), API setting records (inbound and outbound), and content versions (files).

Example

apex
User testUser = TST_Factory.insertUser('Standard User');

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 User insertUser(String profileName)Creates and saves a single User record with the specified profile, inside the factory's own guard, ready for System.runAs.
global static User insertUser(String profileName, String companyName)Creates and saves a User record with a custom company name, inside the factory's own guard.
global static List<User> insertUsers(List<User> users)Saves the given User records inside the factory's own guard, so a test can save ordinary records before or after this call in the same transaction without a System.runAs block of its own.
global static List<User> insertUsers(String profileName, Integer numberOfUsers)Creates and saves a list of User records with the specified profile, inside the factory's own guard.
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 newDisabledFeatureFlag(String flagName)Turns a feature flag off for the rest of the test, whatever its deployed record says.
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 so that a query in the test returns it.
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 so that a query in the test returns it.
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 so that a query in the test returns it.
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. The assignments are saved in one statement, inside the factory's own guard while a test runs, so ordinary records a test saves before or after this call in the same transaction do not collide with them.

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.insertUsers('Standard User', 2);
PermissionSet permissionSet = new SEL_PermissionSet().findByName('CustomPermissionSet');
TST_Factory.createPermissionSetAssignments(users, permissionSet.Id);
apex
global static void createPermissionSetAssignments(List<User> users, String permissionSetOrGroupName)

Creates PermissionSetAssignment records for a list of users and a permission set. The assignments are saved in one statement, inside the factory's own guard while a test runs, so ordinary records a test saves before or after this call in the same transaction do not collide with them.

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.insertUsers('Standard User', 2);
TST_Factory.createPermissionSetAssignments(users, 'CustomPermissionSet');

insertUser ​

apex
global static User insertUser(String profileName)

Creates and saves a single User record with the specified profile, inside the factory's own guard, ready for System.runAs.

Parameters

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

Returns User — A saved User record.

Throws

ExceptionDescription
DmlExceptionIf the user cannot be saved, for example when no licence seat is free for its profile's licence.

Example

apex
User testUser = TST_Factory.insertUser('Standard User');
System.runAs(testUser)
{
    // test body
}
apex
global static User insertUser(String profileName, String companyName)

Creates and saves a User record with a custom company name, inside the factory's own guard. 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 — A saved User record with the specified company name.

Throws

ExceptionDescription
DmlExceptionIf the user cannot be saved, for example when no licence seat is free for its profile's licence.

Example

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

insertUsers ​

apex
global static List<User> insertUsers(List<User> users)

Saves the given User records inside the factory's own guard, so a test can save ordinary records before or after this call in the same transaction without a System.runAs block of its own. Build the users with newUser or newUsers, set any field your org's User rules need (a role, a required custom field), then hand them here. Each user needs a free licence seat for its profile's licence; the platform's own error is thrown when there is none.

Parameters

ParameterTypeDescription
usersListThe unsaved User records to save.

Returns User — The same records, saved, with Ids.

Throws

ExceptionDescription
DmlExceptionIf a user cannot be saved, for example when no licence seat is free for its profile's licence.

Example

apex
User manager = TST_Factory.newUser('Standard User');
manager.Title = 'Regional Manager';
TST_Factory.insertUsers(new List<User> {manager});
apex
global static List<User> insertUsers(String profileName, Integer numberOfUsers)

Creates and saves a list of User records with the specified profile, inside the factory's own guard.

Parameters

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

Returns User — A list of saved User records.

Throws

ExceptionDescription
DmlExceptionIf a user cannot be saved, for example when no licence seat is free for its profile's licence.

Example

apex
List<User> users = TST_Factory.insertUsers('Standard User', 3);

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;
Assert.isNotNull(apiCall.Id, 'Expected the call record to be saved');
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;
Assert.areEqual('MyService', apiCall.ServiceName__c, 'Expected the given service name');

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 account = (Account)TST_Builder.of(Account.SObjectType).build();
ContentVersion version = TST_Factory.newContentVersion(account.Id, 'test.pdf', Blob.valueOf('Test data'));
insert version;
Assert.areEqual('test.pdf', version.Title, 'Expected the file name to be the title');

newDisabledFeatureFlag ​

apex
global static FeatureFlag__mdt newDisabledFeatureFlag(String flagName)

Turns a feature flag off for the rest of the test, whatever its deployed record says. UTIL_FeatureFlag.isEnabled(flagName) returns false after this call, also for a flag your org ships on and for a flag with strategies: the copy of the flag the test reads has none. Use it to test the code a flag turns off.

Parameters

ParameterTypeDescription
flagNameStringThe developer name of the feature flag to turn off.

Returns FeatureFlag__mdt — The flag record the test now reads, with Enabled By Default unticked.

Example

apex
TST_Factory.newDisabledFeatureFlag('MyFeatureFlag');
Assert.isFalse(UTIL_FeatureFlag.isEnabled('MyFeatureFlag'), 'Expected the flag to be off in this test');

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;
Assert.isNotNull(inboundApiCall.Id, 'Expected the inbound call record to be saved');

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 so that a query in the test returns it.

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 so that a query in the test returns it.

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.LogIssues__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;
Assert.isNotNull(outboundApiCall.Id, 'Expected the outbound call record to be saved');
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 account = (Account)TST_Builder.of(Account.SObjectType).build();
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', account.Id);
insert apiCall;
Assert.isNotNull(apiCall.Id, 'Expected the call record to be saved');
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 account = (Account)TST_Builder.of(Account.SObjectType).build();
Map<String, String> params = new Map<String, String>
{
    'key' => 'value'
};
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', account.Id, params);
insert apiCall;
Assert.isNotNull(apiCall.Id, 'Expected the call record to be saved');
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 account = (Account)TST_Builder.of(Account.SObjectType).build();
ApiCall__c apiCall = TST_Factory.newOutboundApiCall('OutboundService', account.Id, 'key', 'value');
insert apiCall;
Assert.isNotNull(apiCall.Id, 'Expected the call record to be saved');

newOutboundApiSetting ​

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

Creates a mock outbound ApiSetting__mdt record via TST_Mock so that a query in the test returns it. 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;
Assert.isNotNull(testUser.Id, 'Expected the user to be saved');
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)
{
Assert.isNotNull(u.Id, 'Expected each user to be saved');
}

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 insertUser(profileName, companyName) and createPermissionSetAssignments(List , String), so both setup writes run inside the factory's own guard and the test can save ordinary records before or after this call in the same transaction.

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,
            'Administrator'
    );
}
private static User getTestAdmin()
{
    return new SEL_User().findByCompanyName(TEST_ADMIN_COMPANY);
}
@IsTest
private static void shouldDoX()
{
    System.runAs(getTestAdmin())
    {
        // test body
    }
}