Sub topic 10
Testing as a specific user with System.runAs
This chapter assumes you can write an @IsTest method, use @TestSetup, and call the Assert class. It also assumes you know what with sharing means. Tests normally run as the user who started the test run, usually an administrator who can see and edit nearly everything. A test that only runs as that user can pass even when the code fails for real users. System.runAs runs a block of code as another user, so you can test what that user sees and does.
What runAs changes and what it leaves alone
System.runAs(user) { ... } runs the statements in the block in the context of the given user. Code inside the block that uses with sharing applies that user's record access. Calls to UserInfo.getUserId() return that user's Id.
runAs does not change everything. The table lists the main points.
| Aspect | Inside a runAs block |
|---|---|
| Record sharing (`with sharing` classes) | Enforced for the given user |
| `UserInfo` values (user Id, profile Id, locale) | Reflect the given user |
| Object and field permissions (CRUD and FLS) | Not enforced by `runAs` alone. Code must ask for them, for example with `WITH USER_MODE` |
| Governor limits | Same transaction, same limits. `runAs` does not reset them |
| User license limits | Ignored, so you can create test users even if the org has no spare licenses |
| Mixed DML restriction | Relaxed, because the block counts as its own context |
The CRUD and FLS row catches many developers. A profile with no access to Account does not make an Account query fail inside runAs. The query fails only if the code under test enforces permissions itself.
The basic pattern
The pattern has four steps:
- Create a user with a known profile.
- Insert the user.
- Run the code under test inside
runAs. - Assert on what happened.
The spine example does this with a Standard User:
@IsTest
static void runsAsStandardUser() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
System.runAs(u) {
Assert.areEqual(u.Id, UserInfo.getUserId(), 'Code should run as the test user');
}
}The UserName field must be unique across all Salesforce orgs, so the test appends a timestamp. Two users created in the same millisecond can still collide. A factory that uses a random value avoids that problem (see the next section).
You do not have to insert a user. System.runAs(new User(Id = UserInfo.getUserId())) runs as the current user. This form is mostly useful for the mixed DML case described later.
A user factory
Building a User takes about ten lines. Put those lines in a shared helper, in the same way you would for other test data.
@IsTest
public class TestUserFactory {
public static User createUser(String profileName, String lastName) {
Profile p = [SELECT Id FROM Profile WHERE Name = :profileName LIMIT 1];
String unique = String.valueOf(Math.abs(Crypto.getRandomLong()));
User u = new User(
Alias = 'tstusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = lastName,
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'tstusr' + unique + '@example.com'
);
insert u;
return u;
}
}Profile names can differ between orgs. If a test fails with a QueryException on the profile query, check that the profile exists in the org that runs the tests.
Testing record sharing
The most common reason to use runAs is to check that a with sharing class hides records from users who should not see them. The class below returns every account the current user can see.
public with sharing class AccountReader {
public static List<Account> visibleAccounts() {
return [SELECT Id, Name FROM Account];
}
}The test creates one account owned by the test runner. It then queries as the test runner and as a second user.
@IsTest
private class AccountReaderTest {
@TestSetup
static void setup() {
insert new Account(Name = 'Owner Only');
}
@IsTest
static void otherUserCannotSeeOwnersPrivateAccount() {
User other = TestUserFactory.createUser('Standard User', 'Outsider');
Assert.areEqual(1, AccountReader.visibleAccounts().size(),
'Control check: the owner should see the account');
System.runAs(other) {
List<Account> seen = AccountReader.visibleAccounts();
Assert.areEqual(0, seen.size(),
'A user outside the owner hierarchy should not see a private account');
}
}
}The first assertion is a control. If the owner could not see the account either, a zero in the second assertion would prove nothing. Check the data first, then check the restriction.
Mixed DML and setup objects
Salesforce splits objects into setup objects, such as User and PermissionSetAssignment, and non-setup objects, such as Account. You cannot insert both kinds in one transaction. A test method that inserts a user and then an account fails with a MIXED_DML_OPERATION error.
There are two ways to avoid the error:
- Insert the non-setup data in
@TestSetup. It is committed before each test method runs, so the method starts clean. - Put one kind of DML inside a
runAsblock. The block counts as its own context.
Permission set assignments are setup objects too. The following test assigns a permission set to a user. It uses Invoice_Approver as a placeholder API name, so replace it with a permission set that exists in your org.
@IsTest
static void permissionSetIsAssigned() {
User u = TestUserFactory.createUser('Standard User', 'Approver');
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = 'Invoice_Approver' LIMIT 1];
System.runAs(new User(Id = UserInfo.getUserId())) {
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);
}
Integer assigned = [SELECT COUNT() FROM PermissionSetAssignment
WHERE AssigneeId = :u.Id AND PermissionSetId = :ps.Id];
Assert.areEqual(1, assigned, 'The permission set should be assigned to the user');
}Testing permissions with user mode
Because runAs does not enforce CRUD or field-level security, a permission test needs two things. The code under test must enforce permissions, and the test must run it as a user who lacks them. Query and DML in user mode (WITH USER_MODE, or AccessLevel.USER_MODE on Database methods) enforce the running user's object and field permissions.
public with sharing class SecureAccountReader {
public static List<Account> readAll() {
return [SELECT Id, Name FROM Account WITH USER_MODE];
}
}The test uses the Minimum Access - Salesforce profile, which grants no object access by default.
@IsTest
static void userWithoutAccountAccessIsBlocked() {
User limited = TestUserFactory.createUser('Minimum Access - Salesforce', 'Limited');
System.runAs(limited) {
try {
SecureAccountReader.readAll();
Assert.fail('Expected a QueryException because the user cannot read Account');
} catch (QueryException e) {
Assert.isTrue(String.isNotBlank(e.getMessage()), 'The exception should carry a message');
}
}
}This is the negative test pattern from the earlier chapter. Assert.fail throws an AssertException, which the QueryException catch block does not catch. If no exception occurs, the test fails.
Common mistakes
- Asserting outside the block by accident. Assertions run as the user in whose context they execute. Put the assertion inside the block if it depends on user context, such as
UserInfo.getUserId(). Assertions on saved data can go inside or after the block. - Skipping the control check. A test that only shows a user sees nothing can pass because the data was never created. Assert the positive case first.
- Expecting
runAsto enforce permissions. WithoutWITH USER_MODE,Security.stripInaccessible, or explicitisAccessible()checks in the code under test, a restricted profile has no effect on CRUD or FLS. - Counting on fresh limits.
runAsshares the transaction's limits. UseTest.startTestandTest.stopTestfor a fresh set. - Duplicate usernames. Use a random or unique suffix, as the factory does.
- Reading org data. Tests do not see existing org data by default. Create everything the test needs, including the records the second user should or should not see.
Exercise
A test inserts a User and then, in the same method, inserts an Account. It fails with MIXEDDMLOPERATION. Give two ways to fix it.
Show answer
Move the Account insert into a @TestSetup method, so it is committed before the test method runs. Or wrap one of the two inserts in System.runAs(new User(Id = UserInfo.getUserId())) { ... } so it runs in its own context.
Exercise
A test runs a with sharing query as a Standard User and asserts the result list has zero records. The test passes, but the developer later learns the test data was never inserted. What change would have caught this, and what assumption about the org does the test rely on?
Show answer
Add a control assertion before the runAs block that shows the owner (the test runner) can see the record, for example Assert.areEqual(1, AccountReader.visibleAccounts().size(), 'Owner should see the account'). The test also relies on the object's organization-wide default being Private. With a public default, the second user would see the record.