How to create Users in Test Class?

on

|

views

and

comments

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

  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
Amit Singhhttps://www.pantherschools.com/
Amit Singh aka @sfdcpanther/pantherschools, a Salesforce Technical Architect, Consultant with over 8+ years of experience in Salesforce technology. 21x Certified. Blogger, Speaker, and Instructor. DevSecOps Champion
Share this

Leave a review

Excellent

SUBSCRIBE-US

Book a 1:1 Call

Must-read

How to Utilize Salesforce CLI sf (v2)

The Salesforce CLI is not just a tool; it’s the cornerstone of development on the Salesforce Platform. It’s your go-to for building, testing, deploying, and more. As one of the most important development tools in our ecosystem

Save the day of a Developer with Apex Log Analyzer

Table of Contents What is Apex Log Analyzer? Apex Log Analyzer, a tool designed with Salesforce developers in mind, is here to simplify and accelerate your...

Salesforce PodCast

Introduction Hey Everyone, Welcome to my podcast, the first-ever podcast in India for Salesforce professionals. Achievement We are happy to announce that we have been selected as Top...

Recent articles

More like this

LEAVE A REPLY

Please enter your comment!
Please enter your name here

5/5

Stuck in coding limbo?

Our courses unlock your tech potential