Introductoion
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
- roleId – The Id of the Role if Applicable otherwise pass blank string
- profileId – The Id of the Profile and it is Mandatory to pass
- firstName – FirstName of the User
- 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 addPermissionSet(String userId, List permissionSetIds ){
List permissionsSets = new List();
for(String ids : permissionSetIds){
PermissionSetAssignment permSet = new PermissionSetAssignment();
permSet.AssigneeId = userId;
permSet.PermissionSetId = ids;
permissionsSets.add(permSet);
}
return permissionsSets;
}
public static List addGroupMembers(String userId, List groupIds){
List groupMembers = new List();
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 addPermissionSet(String userId, List permissionSetIds ){
List permissionsSets = new List();
for(String ids : permissionSetIds){
PermissionSetAssignment permSet = new PermissionSetAssignment();
permSet.AssigneeId = userId;
permSet.PermissionSetId = ids;
permissionsSets.add(permSet);
}
return permissionsSets;
}
public static List addGroupMembers(String userId, List groupIds){
List groupMembers = new List();
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.