Sub topic 11
Testing as a specific user with System.runAs
This chapter assumes you can write a basic Apex test class and know the difference between sharing and field-level security. By default, Apex tests run as the user who started the test run, usually an administrator. A test that passes for an administrator can hide bugs that affect ordinary users. System.runAs lets a test switch to another user for a block of code.
What runAs changes
System.runAs(user) runs a block of code as the given user. Inside the block:
- Record sharing for that user is enforced for classes declared
with sharing. UserInfo.getUserId()and similar methods return that user.- Setup and non-setup DML can be mixed, which avoids the
MIXED_DML_OPERATIONerror.
runAs does not enforce object permissions or field-level security on its own. Your code must do that, for example with WITH USER_MODE in SOQL or Security.stripInaccessible. runAs only makes sure the code sees the right user when it checks.
Creating a test user
Create the user in the test. Don't query a real user, because real users differ between orgs. The profile name must exist in every org where the test runs, and Standard User is a safe choice. The username must be unique across all Salesforce orgs, so add a changing value.
@isTest
private class RunAsSharingTest {
private static User buildUser(String alias) {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
String unique = alias + String.valueOf(System.currentTimeMillis());
return new User(
Alias = alias,
LastName = 'Tester ' + alias,
Email = unique + '@example.com',
Username = unique + '@example.com',
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles',
ProfileId = p.Id
);
}
@isTest
static void userCannotSeeAnotherUsersPrivateAccount() {
User owner = buildUser('own');
User other = buildUser('oth');
insert new List<User>{ owner, other };
System.runAs(owner) {
insert new Account(Name = 'Owner Only');
}
System.runAs(other) {
Integer visible = [SELECT COUNT() FROM Account WHERE Name = 'Owner Only'];
Assert.areEqual(0, visible, 'A second user should not see a private account');
}
}
}This test assumes the org-wide default for Account is Private. If your org uses Public Read Only, the second user can see the account and the assertion fails. A test like this documents a sharing assumption, so state it in the assertion message or a comment.
Assigning permission sets
To test behavior that depends on a permission set, insert a PermissionSetAssignment for the test user. Do this before the runAs block.
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = 'Discount_Approver' LIMIT 1];
insert new PermissionSetAssignment(AssigneeId = approver.Id, PermissionSetId = ps.Id);Write one test with the permission set and one without it. Together they show that the feature works for the right users and is blocked for the others.
Common mistakes
| Mistake | Effect |
|---|---|
| Testing only as an administrator | Sharing and permission bugs are never exercised |
| Reusing a fixed username | Insert fails when the username already exists in another org |
| Expecting `runAs` to enforce field-level security | The code under test reads or writes fields it should not |
| Using `runAs` on code that is `without sharing` | Sharing is not applied, so the test proves nothing about visibility |
Exercise
A test creates an Account as an administrator, then uses System.runAs with a Standard User and queries the account inside a class declared "with sharing". The query returns 1 row, but you expected 0. Name two possible causes.
Show answer
The org-wide default for Account may be Public Read Only or Public Read/Write, so the user can see the record. Or the class is not actually enforcing sharing (for example it is "without sharing"). The user may also have access through a role hierarchy, sharing rule or "View All" permission.