APEX test user creation

Taken from the documentation:

Generally, all Apex code runs in system mode, where the permissions and record sharing of the current user are not taken into account. The system method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.

You can use runAs only in test methods. The original system context is started again after all runAs test methods complete.

The runAs method ignores user license limits. You can create new users with runAs even if your organization has no additional user licenses.

@isTest
private class TestRunAs {
    public static testMethod void testRunAs() {
        // Setup test data
        // This code runs as the system user
        Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        User u = new User(Alias = 'standt', Email='[email protected]', 
            EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
            LocaleSidKey='en_US', ProfileId = p.Id, 
            TimeZoneSidKey='America/Los_Angeles', UserName='[email protected]');

        System.runAs(u) {
            // The following code runs as user 'u' 
            System.debug('Current User: ' + UserInfo.getUserName());
            System.debug('Current Profile: ' + UserInfo.getProfileId()); 
        }
    }
}

Building on this answer, I construct my test classes @TestSetup methods such that I can create an arbitrary number of unique users using a shortened 8-char GUID to init the names and emails, like so:

@IsTest  
public with sharing class NotificationTests {
  @TestSetup  
  private static void setup() {    
    // Setup 4 Test Users
    Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
    List<User> uu = new List<User>();

    while (uu.size() < 5) {
      Blob b = Crypto.GenerateAESKey(128);
      String h = EncodingUtil.ConvertTohex(b);
      String uid = h.SubString(0,8);
      User u = new User(Alias = uid, Email= uid + '@myorg.com', 
          EmailEncodingKey='UTF-8', LastName='Testing', LanguageLocaleKey='en_US', 
          LocaleSidKey='en_US', ProfileId = p.Id, 
          TimeZoneSidKey='America/New_York', UserName= uid + '@myorg.com');      
      uu.add(u);
    }
    insert(uu);
  }

  @IsTest
  public static void myTest() {
    /* ... */
  }
}

Tags:

User

Unit Test