Apex Testing: Username Creation Best Practice

One common testing need is security testing. When a given user goes to Page X, they can only access and perform Y actions. Salesforce’s Apex Testing capabilities makes this painless. Through one or more test methods, users records are temporarily created and then verified that they can or cannot do the expected actions. This allows implementors to verify that their security model is correct or that it needs changing. 

​When creating these users, the username for each user must be globally unique. I.e. The username must not only be unique across your Salesforce instance / org, but all Salesforce instances / orgs. In An Introduction to Apex Code Test Methods, the canonical example is to create a user with a “standarduser@testorg.com” username. However, it’s very likely that someone has already created a real user with that username and if your testmethod tries to create a test user with an existing username, a “Duplicate User” error is thrown.

Username Creation

The solution is to use dynamic data to guarantee, or at least make it extremely probable, that a username is unique. One solution is to use the Org Id and a timestamp as a prefix and prepend that to the username. Here’s some sample code using the DataFactory Design Pattern combined with the example from An Introduction to Apex Code Test Methods:
public class DataFactoryUser {
    // This method dynamically creates a username prefix that will make ensure username uniqueness.
    public static String getUserNamePrefix(){
        return UserInfo.getOrganizationId() + System.now().millisecond();
    // Other create and insert methods here…
    public static User insertStandardUser(Id standardProfileId){
        // assert standardProfileId valid
        User standardUser = new User(
          Username = getUserNamePrefix() + ‘standarduser@testorg.com’,
          Alias = ‘standt’,
          email = ‘standarduser@testorg.com’,
          emailencodingkey = ‘UTF-8’,
          LastName = ‘Testing’,
          Language = ‘en_US’,
          LocaleSidKey = ‘en_US’,
          Profile = standardProfileId,
          TimeZoneSidKey = ‘America/Los_Angeles’
        insert standardUser;
        return standardUser;
Have other solutions to ensure unique usernames? Perfect, please share them.
Happy Coding & Testing,

Stay on top of the latest and greatest. Sign up now.

Recommended for you

Blog Subscribe

This will close in 0 seconds