Sub topic 10
Testing as a specific user with System.runAs
This chapter assumes you can write an @IsTest method, insert records in a test, and use Assert.areEqual. It also assumes you know that Apex normally runs in system mode, which ignores the running user's permissions.
Why test as another user
A test method runs as the user who started the test run. That user is usually an administrator, so the code under test sees every object and record. A test that passes for an administrator can still fail for a Standard User. System.runAs(user) runs a block of code with that user's record sharing and permissions, so you can check what a real user would get.
System.runAs has two main uses:
- Testing sharing behavior. Classes declared
with sharingrespect the running user's record access. - Testing permission checks. This includes
WITH USER_MODEqueries,Schema.sObjectTypedescribe checks, and permission sets.
Creating a test user
Create the user inside the test. Test data does not persist after the test ends, so the user disappears too. The user needs a profile, a unique username, and the required fields.
@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');
}
}Usernames must be unique across all Salesforce orgs. Adding System.currentTimeMillis() avoids collisions between runs.
The assertion inside the block confirms that the context switched. Real tests call the code under test inside the block and assert on what that user can do.
What runAs changes and what it does not
The table below summarizes the behavior.
| Aspect | Effect of `System.runAs` |
|---|---|
| Record sharing | Enforced for `with sharing` classes, for the specified user |
| Profile and permission sets | Those of the specified user apply to permission-aware code |
| Governor limits | Not reset. Use `Test.startTest` for that |
| Mixed DML restriction | Setup and non-setup objects can be mixed when the setup DML is inside the `runAs` block |
| Login or session | Not created. Only the user context changes |
Records inserted before the runAs block still exist inside it. Whether the user can see them depends on sharing rules and on who owns them.
Mixed DML errors
Salesforce does not allow DML on setup objects, such as User, and non-setup objects, such as Account, in one transaction. A test that inserts a user and then an account can fail with a MIXED_DML_OPERATION error. Wrapping the setup DML in a System.runAs block avoids this. Using the current user is enough:
@IsTest
static void insertsUserAndAccount() {
User admin = new User(Id = UserInfo.getUserId());
System.runAs(admin) {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'mixed',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'Mixed',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'mixed' + System.currentTimeMillis() + '@example.com'
);
insert u;
}
insert new Account(Name = 'Acme');
Assert.areEqual(1, [SELECT COUNT() FROM Account], 'The account should be saved');
}Common mistakes
- Creating the user outside the test and expecting it to exist. Test data is rolled back and cannot be shared between tests, except through
@TestSetup. - Asserting only that
runAsran. Always call the code under test inside the block and check its result. - Hard-coding a username. This fails on the second run in the same org.
- Assuming
runAsresets limits. It does not.
Exercise
A class uses WITH USER_MODE in a SOQL query on Contact. You want to prove a user without read access to Contact gets an error. Why is running the test with no System.runAs unreliable, and what should the test do?
Show answer
Without runAs, the test runs as the person who started the test run, usually an administrator who can read Contact, so the query succeeds and the error path is never exercised. The test should create a user whose profile or permission sets lack Contact read access, call the class inside System.runAs(thatUser), wrap the call in try/catch, call Assert.fail after the call, and assert on the caught exception type and message.