Using the runAs Method
Generally, all Apex code runs in user mode, where the object-level and field-level permissions of the current user are enforced. With the System method runAs, you can write test methods that change the user context to an existing user or a new user. Then that user’s sharing rules and object-level and field-level permissions are enforced.
The user’s sharing rules and object-level and field-level permissions are enforced within a runAs block, regardless of the sharing mode (with sharing or without sharing) of the test class.
If a user-defined method is called in the runAs block, the sharing mode enforced is that of the class where the method is defined, not the test class.
You can use runAs only in test methods. The original current user context is started again after all runAs test methods complete.
The runAs method ignores user license limits. You can create users with runAs even if your organization has no additional user licenses.
Every call to runAs counts against the total number of DML statements issued in the process.
In the following example, a new test user is created, then code is run as that user, with that user’s record sharing access:
You can nest more than one runAs method. For example:
You can also use the runAs method to perform mixed DML operations in your test by enclosing the DML operations within the runAs block. In this way, you bypass the mixed DML error that is otherwise returned when inserting or updating setup objects together with other sObjects. See sObjects That Cannot Be Used Together in DML Operations.
There’s another overload of the runAs method (runAs(System.Version)) that takes a package version as an argument. This method causes the code of a specific version of a managed package to be used. For information on using the runAs method and specifying a package version context, see Testing Behavior in Package Versions.
See Also