Free computer code on screen

Employing the runAs Method in Salesforce A Guide for Apex Developers

By and large, Apex code generally operates within the framework mode, where the current user’s permissions and record access are not taken into account. The framework method known as runAs enables you to construct test methods that temporarily change the user context to that of an existing or alternate user. This facilitates enforcement of the user’s record sharing settings. It’s important to note that the runAs method does not enforce user permissions or field-level permissions, but solely focuses on record sharing.

The runAs method is exclusively available for use within test methods. The original framework context is reinstated after all runAs test methods have concluded.

Furthermore, the runAs method circumvents user license limitations. You can generate new users using runAs even if your organization has no available additional user licenses.

It’s noteworthy that each invocation of runAs contributes to the total count of simultaneous DML statements executed.

In the provided example, a new test user is generated, and subsequently, code is executed within the context of that user, utilizing their specific record sharing permissions:

@isTest 
private class TestRunAs { 
    public static testMethod void testRunAs() { 
        //Setup test information 
        //Create an interesting UserName 
        String uniqueUsName = 'sample' + DateTime.now().getTime() + '@test.com'; 
        //This code runs as the framework client 
        Profile getprofile = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        Client currentUser = new User(Alias = 'testus', Email='testuser@test.com', 
        EmailEncodingKey='UTF-8', LastName='sample', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = getprofile.Id, 
        TimeZoneSidKey='America/Los_Angeles', 
        UserName=uniqueUsName); 
        System.runAs(currentUser) { 
            /The accompanying code runs as client 'u' 
            System.debug( UserInfo.getUserName()); 
            System.debug( UserInfo.getProfileId()); 
        } 
    } 
}

Multiple runAs methods can be employed. For instance:

@isTest 
private class TestRunAs2 { 
    public static testMethod void test2() { 
        Profile getprofile = [SELECT Id FROM Profile WHERE Name='Standard User']; 
        Client currentUser2 = new User(Alias = 'testus2', Email='testuser2@test.com', 
        EmailEncodingKey='UTF-8', LastName='sample 2', LanguageLocaleKey='en_US', 
        LocaleSidKey='en_US', ProfileId = getprofile.Id, 
        TimeZoneSidKey='America/Los_Angeles', UserName='newsampleuser@test.com'); 
        System.runAs(currentUser2) { 
            /The accompanying code runs as client currentUser2. 
            System.debug(UserInfo.getUserName()); 
            System.debug(UserInfo.getProfileId()); 
            //The accompanying code runs as client currentUser3. 
            System.runAs(currentUser3) { 
                System.debug(UserInfo.getUserName()); 
                System.debug( UserInfo.getProfileId()); 
            } 
            //Any extra code here would run as client currentUser2. 
        } 
    } 
}

Diverse Applications of the runAs Method

The runAs method can also be utilized to carry out mixed DML operations within your test code by encapsulating the DML actions within the runAs block. By doing so, you can bypass the typical mixed DML error that arises when inserting or updating setup objects in conjunction with other sObjects.

Additionally, there is another variation of the runAs method (runAs(System.Version)) which accepts a package version as an argument. This version of the method allows for the execution of code from a specific version of a managed package. For more information on using the runAs method and specifying a package version, refer to ‘Testing Behavior in Package Versions’.

Evaluating Functionality Across Package Versions in Testing

When modifying the behavior within an Apex class or trigger for various package versions, it’s essential to verify that your code performs as expected across these distinct package iterations. You can craft test methods that alter the package version context to target a different package version by employing the system method runAs. This approach can exclusively be used within a test method.