How to create Users in Test Class?

AMIT SINGH
3 min readDec 26, 2022

--

Creating the users in the test class is very critical and important because we should always unit test our apex code with runAs methods in our test class.

In this blog post, we will talk about how to create a user inside the test class and use it for testing the functionality requirements.

Required Parameters for users

To create any object records inside salesforce, it is very important to know that are all the required fields either from the field level or from the validation rules.

Below are the required fields for the user object in Salesforce.

Click here to know all the required fields and valid picklist values.

Create Utility Class

In your projects, there will be multiple functionalities where you need to use runAs method for testing the functionality.

So it is better to create a utility class that will provide the re-usable methods to perform the necessary operations.

Prepare users inside the test method

public static User prepareUser(String roleId, String profId, String firstName, String lastName) {    String orgId = UserInfo.getOrganizationId();
String dateString =
String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
String uniqueName = orgId + dateString + randomInt;
User tempUser = new User(
FirstName = firstName,
LastName = lastName,
email = uniqueName + '@sfdc' + orgId + '.org',
Username = uniqueName + '@sfdc' + orgId + '.org',
EmailEncodingKey = 'ISO-8859-1',
Alias = uniqueName.substring(18, 23),
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US',
ProfileId = profId
);
if( String.isBlank(roleId) == false ){
tempUser.UserRoleId = roleId;
}
return tempUser;
}

The method takes 4 parameters

  1. roleId — The Id of the Role if Applicable otherwise pass blank string
  2. profileId — The Id of the Profile and it is Mandatory to pass
  3. firstName — FirstName of the User
  4. lastName — LastName of the User

Add additional information if needed

After we create the user, sometimes we need to assign permission sets or groups to the user for proper visibility and security.

For this, we have created a couple of methods that prepare the required objects and return the list of objects.

public static List<PermissionSetAssignment> addPermissionSet(String userId, List<String> permissionSetIds ){
List<PermissionSetAssignment> permissionsSets = new List<PermissionSetAssignment>();
for(String ids : permissionSetIds){
PermissionSetAssignment permSet = new PermissionSetAssignment();
permSet.AssigneeId = userId;
permSet.PermissionSetId = ids;
permissionsSets.add(permSet);
}
return permissionsSets;
}
public static List<GroupMember> addGroupMembers(String userId, List<String> groupIds){
List<GroupMember> groupMembers = new List<GroupMember>();
for(String groupId : groupIds){
GroupMember gm = new GroupMember();
gm.GroupId = groupId;
gm.UserOrGroupId = userId;
groupMembers.add(gm);
}
return groupMembers;
}

There are two methods both methods accept 2 parameters first for userId and second to prepare either permission set assignment or public group assignment.

Complete Utility Class

/**
* @description :
* @author : Amit Singh
* @group :
* @last modified on : 08-25-2022
* @last modified by : Amit Singh
**/
@IsTest
public with sharing class TestUserUtility {
public static User prepareUser(String roleId, String profId, String firstName, String lastName) {
String orgId = UserInfo.getOrganizationId();
String dateString =
String.valueof(Datetime.now()).replace(' ','').replace(':','').replace('-','');
Integer randomInt = Integer.valueOf(math.rint(math.random()*1000000));
String uniqueName = orgId + dateString + randomInt;
User tempUser = new User(
FirstName = firstName,
LastName = lastName,
email = uniqueName + '@sfdc' + orgId + '.org',
Username = uniqueName + '@sfdc' + orgId + '.org',
EmailEncodingKey = 'ISO-8859-1',
Alias = uniqueName.substring(18, 23),
TimeZoneSidKey = 'America/Los_Angeles',
LocaleSidKey = 'en_US',
LanguageLocaleKey = 'en_US',
ProfileId = profId
);
if( String.isBlank(roleId) == false ){
tempUser.UserRoleId = roleId;
}
return tempUser;
}
public static List<PermissionSetAssignment> addPermissionSet(String userId, List<String> permissionSetIds ){
List<PermissionSetAssignment> permissionsSets = new List<PermissionSetAssignment>();
for(String ids : permissionSetIds){
PermissionSetAssignment permSet = new PermissionSetAssignment();
permSet.AssigneeId = userId;
permSet.PermissionSetId = ids;
permissionsSets.add(permSet);
}
return permissionsSets;
}
public static List<GroupMember> addGroupMembers(String userId, List<String> groupIds){
List<GroupMember> groupMembers = new List<GroupMember>();
for(String groupId : groupIds){
GroupMember gm = new GroupMember();
gm.GroupId = groupId;
gm.UserOrGroupId = userId;
groupMembers.add(gm);
}
return groupMembers;
}
}

Prepare the test class

Now, we have prepared the utility class. The time is to create the test class and use these methods inside the test class.

/**
* @description :
* @author : Amit Singh
* @group :
* @last modified on : 08-25-2022
* @last modified by : Amit Singh
**/
@IsTest
public class AcountHelperClassTest {
@IsTest
public static void createUser(){
Id profileId = [Select Id From Profile Where Name ='Standard Platform User']?.Id;
User u = TestUserUtility.prepareUser('',profileId,'Amit','Singh');
System.runAs( u ){
Account acc = new Account(
Name = 'Salesforce.com',
Rating = 'Hot',
Industry = 'Education',
Phone = '999-888-9999',
Description = 'Salesforce.com is a world leading CRM company'
);
insert as user acc;
System.assertNotEquals(null, acc.Id, 'The account id is null');
}
}
}

Create Community User in Test Class

Refer to this Link for creating the Community users in Salesforce Test Class.

--

--

AMIT SINGH

Software Developer by day & YouTube by night. Salesforce Architect || Salesforce MVP || Integration Expert