What is the System.runAs() Method in Salesforce Apex Class?

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.

Note: We 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. We can create new users with runAs even if your organization has no additional user licenses.

The following items use the permissions granted by the user specified with runAs running as a specific user:

  • dynamic Apex
  • methods using with sharing or without sharing
  • shared records

Example:

In the following example, a new test user is created, then code is run as that user, with that user’s record sharing access:

@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 Test User']; 
      User u = new User(Alias = 'standt', Email='standardtestuser@force.com', 
      EmailEncodingKey='UTF-8', LastName='TestUser', LanguageLocaleKey='en_US', 
      LocaleSidKey='en_US', ProfileId = p.Id, 
      TimeZoneSidKey='America/Los_Angeles', UserName='standardtestuser@force.com');

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