I was working as a Salesforce Developer, and recently, I was required to add new users to Salesforce programmatically. For that, I developed Apex code to create new users. In this tutorial, I will explain how to create a new user using Salesforce Apex.
Create a New User With a Password Using Salesforce Apex
In the following Apex program, I explained how to create a new user using a class and methods.
Here, I created an Apex class with a method. I first created a variable named profileId with Profile as the data type in that method. In this variable, we stored the profile ID fetched by SOQL, which we will assign to the new user.
Next, we create an instance of the User object to assign values to its fields.
We will assign values to the user object fields using the object instance. Here, you need to assign all mandatory field values; after that, only your user will be created. Then, ensure you enter a unique username because duplicate usernames are not allowed in Salesforce.
Then, I created a try block, which executes the logic or execution part of the code. If there is an error, the catch block gets executed and throws an error message without interrupting the code’s execution.
In the try block, I executed the Insert DML operation, which created the record or user in the Salesforce org.
Then, we set a temporary password so the user could log in with it. The catch block will execute if any error occurs while inserting the record into the Salesforce database.
After that, save the Apex code and execute the program from the anonymous window.
public class CreateNewUser {
public void CreateUser(){
Profile profileId = [Select Id FROM Profile WHERE Name = 'Identity User' LIMIT 1];
User user = new User();
user.FirstName = 'Alex';
user.LastName = 'Smith';
user.Alias = 'asmith';
user.Username = 'alex.smith@gmail.com';
user.Email = 'alex.smith@gmail.com';
user.ProfileId = profileId.Id;
user.LocaleSidKey = 'en_US';
user.EmailEncodingKey = 'UTF-8';
user.TimeZoneSidKey = 'America/Los_Angeles';
user.LanguageLocaleKey = 'en_US';
try {
insert user;
system.setPassword(user.Id,'NewUserPass@1234');
system.debug('User created successfully with Id: ' + user.Id+ ' & ' + user.Name);
system.debug('The temporary password is: NewUserPass@1234, You can change it
later.');
}
catch (DmlException e) {
System.debug('Error creating user: ' + e.getMessage());
}
}
}
As you navigate to the User details, you will see that the user has been created with values that you assigned in the apex code to the user fields.
The newly created user can log in with their username and temporary password that we provided. As they log in with those credentials, they need to change the password immediately.

In this way, we can create a user with a password in Salesforce using the Apex program.
Create User Using Apex Test Class in Salesforce
In Salesforce, the test class is used to verify the functionality, performance, and security of the custom code. It is usually used to validate that the logic we enter in the code executes as expected. This is required when we deploy the Apex code to the Salesforce org.
In the following program, I created a user using the Apex test class, validating our code with the expected output and logic or values we want to insert into the Salesforce database.
Create User From Class in Salesforce
First, we need to create an Apex class to create a new user. Here, I created a class named CreateUser with a static method named createNewUser() and a User object as a return type. Then, write the code for creating a new user, as I explained in the above Apex program.
public class CreateUser {
public static User createNewUser() {
Profile profile = [SELECT Id FROM Profile WHERE Name = 'Identity User' LIMIT 1];
User newUser = new User();
newUser.FirstName = 'Ella';
newUser.LastName = 'Edward';
newUser.Email = 'ellaedward@gmail.com';
newUser.Username = 'ellaedward@gmail.com';
newUser.Alias = 'ellae';
newUser.ProfileId = profile.Id;
newUser.TimeZoneSidKey = 'America/Los_Angeles';
newUser.LocaleSidKey = 'en_US';
newUser.EmailEncodingKey = 'UTF-8';
newUser.LanguageLocaleKey = 'en_US';
Insert newUser;
system.debug('User is successfully creatred');
return newUser;
}
}Create an Apex Test Class in Salesforce
Now, we will create a Test Class, for which we need to add the @isTest annotation at the top of the class name. We also add this annotation before the method starts, so it will become the test method.
Now, to test whether the user is created with all values entered in the user fields, we created one static method named testCreateUser() with the @isTest annotation. This is a static method with a return type of void because the test method should return nothing, and it should be a static method.
Then, we need to call the createNewUser() method, which we created in the CreateUser class. For that, we need to create a variable(newUser) with the data type User. Next, create a SOQL query to retrieve user details from the class mentioned above and pass the ID through a variable.
System.assertEquals (‘Expected Value’, Actual Value, ‘Optional Message’): The system class has a method called Assert. Using it, we can flag whether the test is a success or a failure while testing. Here, we can compare the results with the expected results of a particular test.
Then, save the program. Now, I will explain how to run the test class.
@isTest
public class TsetNewUser{
@isTest
static void testCreateUser() {
User newUser = CreateUser.createNewUser();
User createdUser = [SELECT Id, FirstName, LastName, Alias, ProfileId FROM User WHERE Id
= :newUser.Id];
System.assertEquals ('Ella', createdUser.FirstName, 'Firstname is incorrect');
System.assertEquals ('Edward', createdUser.LastName, 'Last name is not matched');
System.assertEquals ('ellae', createdUser.Alias);
//Like this add more fields that you want to test.
}
}Run the Apex Test Class on the Developer Console
To run the test class, click the Test option from the menu bar. Then click the New Run option.

Then select the Test class you created; as you click on it, you will see the methods you created in that test class. Now, you need to select which method you want to test. Select those methods; you can select all if you have multiple methods.
Finally, click the Run button to execute the test class and method.

If the code has no problem errors, the status will show a success mark.

Now, to check whether the test failed, I changed the expected value of user Alias from’ ellae’ to ‘sStark’ and again ran the test class as I explained in the above steps.

Now, this time here, the test class fails, and to check the error, double-click on the class name where we get the test class failed.

In the Error column, you can see the error message explaining why the test class failed. Now, you need to correct that error.

After successfully executing the test class, you are ready to execute the CreateUser class. Open an anonymous window and execute the class. You will see the debug statement message if a user is created.

As you navigate to User from Setup, you will see that a new user has been successfully created with the values we assigned to the fields in the Apex program.

In this way, we can create a test class to create new users from Salesforce Apex.
Create Multiple Users From Salesforce Apex
When you want to create multiple users only using the Apex class, there is only one way to do so: you need to declare the User object instance repeatedly, and then you can create multiple users by assigning values to variables or user fields.
For example, in the following Apex class, I explained how to create multiple users from Salesforce Apex. Now, we have created a class and a method. In this method, we first created a user list named NewUserList.
As I explained in the above example, we need to write SOQL to retrieve the profile ID, which we can then use to assign the profile to new users.
Next, create an instance of the User object to assign values to its fields. However, we need to create the number of instances equivalent to the number of users we want to create. Next, assign values to the user fields, ensuring you include all mandatory fields required to create a user.
After assigning values to the user fields, we need to add the user to the created list. That means as many users as we create, all users should be added to the list.
This is because creating more than 150 users and using the Insert DML operation for each user separately would break the governor limit. Therefore, we add the users to the list.
As shown in the try block, I used the Insert operation only once, and all users you added will be created in the Salesforce org.
Then, save the program and execute it.
public class CreateMultipleUser {
public void MultipleUsers() {
List<User> NewUserList = new List<User>();
Profile profileId = [SELECT Id FROM Profile WHERE Name = 'Identity User' LIMIT 1];
User user1 = new User();
user1.FirstName = 'Jonny';
user1.LastName = 'Wed';
//All Mandatory Details of user object;
NewUserList .add(user1);
User user2 = new User();
user2.FirstName = 'Stive';
user2.LastName = 'stark';
NewUserList .add(user2);
// Add more Users you want;
try {
insert NewUserList;
System.debug( 'All Users created successfully for Indentity Profile.' );
}
catch (DmlException e) {
System.debug( 'Their is somthing worng: ' + e.getMessage() );
}
}
}In this way, we can create multiple records using Apex in Salesforce.
Conclusion
I hope you have a good understanding of creating a user from the Salesforce Apex class. In that, I explained how to create a new user using Salesforce Apex. Then, there is another way to create a user by using a test class.
In that, I explained how to create a class to create a new user and then create a test class to check whether the code we entered matches the expected result. Then, we saw how to run the test class on the developer console.
After that, I explained how to create multiple users in Salesforce using the Salesforce Apex class, the List collection, and SOQL.
You may like to read:
- Get Current User Info Using Apex in Salesforce
- List Collection in Salesforce Apex
- Create Set Collection in Salesforce Apex
- Create Set Collection in Salesforce Apex
I am Bijay Kumar, the founder of SalesforceFAQs.com. Having over 10 years of experience working in salesforce technologies for clients across the world (Canada, Australia, United States, United Kingdom, New Zealand, etc.). I am a certified salesforce administrator and expert with experience in developing salesforce applications and projects. My goal is to make it easy for people to learn and use salesforce technologies by providing simple and easy-to-understand solutions. Check out the complete profile on About us.