Sub topic 11
Testing as a specific user with System.runAs
This chapter assumes you can write an Apex test class with @isTest methods and Assert calls. It also assumes you know the difference between with sharing and without sharing classes, and that you can insert a User record in a scratch org or sandbox. By the end you will be able to run code as another user, build test users, and avoid the mixed DML error.
Why tests need a different user
By default, a test method runs as the user who started the test run, usually an administrator. Apex code runs in system mode, which ignores object and field permissions. An administrator also sees almost every record. A test that only runs as that user can pass while the code fails for the people who actually use it.
System.runAs(user) runs a block of code in the context of another user. It lets you check these things:
- Which records the user can see, for code in a
with sharingclass. - Whether code that enforces object and field access (for example
WITH USER_MODE) blocks or allows the user. - Whether code reads
UserInfo.getUserId()or the user's profile correctly.
What runAs changes
| Behavior | Inside a runAs block |
|---|---|
| `UserInfo.getUserId()` | Returns the user you passed in |
| Record sharing in `with sharing` classes | Evaluated for that user |
| `WITH USER_MODE` queries and DML | Enforce that user's object and field permissions |
| Code in `without sharing` classes | Still ignores sharing |
| Mixed DML restriction | Lifted for the block, so setup and non-setup DML can be separated |
| User license limits | Ignored when you build a test user |
The block ends when the closing brace is reached. The test method then continues as the original user.
Building a test user
You need a profile and a username that is unique across all Salesforce orgs. A factory class keeps this in one place, so every test builds users the same way.
@isTest
public class TestUserFactory {
public static User buildUser(String profileName) {
Profile p = [SELECT Id FROM Profile WHERE Name = :profileName LIMIT 1];
String unique = String.valueOf(Datetime.now().getTime())
+ String.valueOf(Math.abs(Crypto.getRandomInteger()));
return new User(
Alias = 'tuser',
Email = 'tuser' + unique + '@example.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
Username = 'tuser' + unique + '@example.com.test'
);
}
public static void assignPermissionSet(User u, String permissionSetName) {
PermissionSet ps = [
SELECT Id FROM PermissionSet WHERE Name = :permissionSetName LIMIT 1
];
insert new PermissionSetAssignment(
AssigneeId = u.Id,
PermissionSetId = ps.Id
);
}
}buildUser returns an unsaved user, so the caller decides when to insert it. Alias is limited to 8 characters, and LastName, Alias, Email, Username, TimeZoneSidKey, the locale fields, EmailEncodingKey and ProfileId are all required. The test creates the profile name as a string, so use a name that exists in every org you deploy to, such as Standard User.
assignPermissionSet takes the API name of a permission set that already exists in the org. Use it when the behavior you test depends on a permission set rather than a profile.
A worked example
This service queries accounts in user mode, so Salesforce checks the caller's object and field access.
public with sharing class AccountService {
public static List<Account> getAccounts() {
return [SELECT Id, Name FROM Account WITH USER_MODE];
}
}The test checks two cases. A Standard User can read the account they own. A user on the Minimum Access profile has no access to Account, so the query throws.
@isTest
private class AccountServiceTest {
@isTest
static void standardUserReadsOwnAccounts() {
User u = TestUserFactory.buildUser('Standard User');
insert u;
System.runAs(u) {
insert new Account(Name = 'Owned by tester');
List<Account> result = AccountService.getAccounts();
Assert.areEqual(1, result.size(), 'The owner should see their account');
Assert.areEqual(u.Id, UserInfo.getUserId(), 'Block should run as the test user');
}
}
@isTest
static void userWithoutAccountAccessIsBlocked() {
User u = TestUserFactory.buildUser('Minimum Access - Salesforce');
insert u;
System.runAs(u) {
try {
AccountService.getAccounts();
Assert.fail('Expected a QueryException for a user without Account access');
} catch (QueryException e) {
Assert.isTrue(e.getMessage().length() > 0, 'The exception should carry a message');
}
}
}
}The Assert.fail call inside the try block matters. Without it, the test would pass if the query unexpectedly succeeded, because nothing would be asserted.
Avoiding the mixed DML error
Salesforce splits objects into setup objects, such as User, PermissionSetAssignment and Group, and non-setup objects, such as Account and Contact. You cannot insert both kinds in one transaction. Doing so raises MIXED_DML_OPERATION.
The error appears in tests when you insert an Account, then a User, in the same method. There are two fixes:
- Insert setup records first, before any non-setup DML. The tests above work this way.
- Wrap the setup DML in its own
runAsblock. Running as the current user is enough.
@isTest
private class MixedDmlTest {
@isTest
static void setupAndNonSetupRecordsTogether() {
insert new Account(Name = 'Created first');
User u = TestUserFactory.buildUser('Standard User');
System.runAs(new User(Id = UserInfo.getUserId())) {
insert u;
TestUserFactory.assignPermissionSet(u, 'Sample_Permission_Set');
}
System.runAs(u) {
Assert.areEqual(u.Id, UserInfo.getUserId(), 'Block should run as the test user');
}
}
}This test assumes your org has a permission set with the API name Sample_Permission_Set. Replace it with a real one, or remove that line.
The same limit applies in @TestSetup methods. If a setup method inserts users, put those inserts in their own runAs block or before the non-setup inserts.
Common mistakes
- Expecting runAs to enforce permissions. If your class is
with sharingbut uses plain SOQL, a user with no Account permission can still read accounts they can see through sharing. The test will pass, and it will not prove the permission check you wanted. - Testing sharing with an admin-owned record. Create the record as one user, then query as another. If both users can see everything through role hierarchy or an open organization-wide default, the test proves nothing. Check the sharing model of the org you test in.
- Hard-coded usernames. A fixed username collides across orgs and across test runs in the same org. Always generate it.
- Asserting outside the block. The
Assertcalls can sit inside or after the block. If you assert onUserInfo.getUserId()after the block ends, you get the original user, so assert inside. - Using runAs to bypass system mode.
runAsdoes not make awithout sharingclass respect sharing. Test that class with the access it really has.
Choosing when to use runAs
Use it when the behavior differs by user: sharing, user-mode access, owner-based logic, or code that reads the current user. Skip it when the code ignores who is running it, because an extra user adds setup cost and a profile dependency. For code with user-dependent branches, write one test per branch, each with its own user.
Exercise
A test method inserts an Account and then inserts a User in the same method, and it fails with MIXEDDMLOPERATION. Give two ways to fix it, and say which part of the test needs a runAs block.
Show answer
Either insert the User (and any PermissionSetAssignment) before any non-setup DML, or wrap the setup DML in System.runAs(new User(Id = UserInfo.getUserId())) so it runs in a separate context from the Account insert. The runAs block is needed only around the setup-object DML. The code under test goes in a second runAs(testUser) block when it must run as the test user.