Sub topic 9
Testing Enforcement with System.runAs
This chapter assumes you can write basic Apex tests, know how profiles and permission sets grant object permissions (CRUD) and field-level security (FLS), and have seen WITH USER_MODE and as user in earlier chapters. Here you will prove that user mode actually blocks access.
Why tests need System.runAs
Apex tests run in system mode, and the test runner is usually a user with broad access. A test that calls AccountService.getAccounts() as that user will pass even if the query has no enforcement at all. To check enforcement, you must run the code as a user who lacks access and confirm that the call fails.
System.runAs(user) does this. Inside its block, Apex runs the code with that user's record sharing, and user mode operations check that user's object permissions and FLS.
The test flow
A permission test has four steps:
- Create a user with a low-privilege profile or permission set.
- Insert the user outside the
runAsblock. - Call the code inside
System.runAs. - Assert on the outcome, either an exception or a restricted result.
A complete negative test
This test uses the Minimum Access - Salesforce profile, which has no access to Account. The service method uses WITH USER_MODE, so the query should throw.
@IsTest
private class AccountServiceTest {
@IsTest
static void queryFailsWithoutAccountAccess() {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Minimum Access - Salesforce' LIMIT 1];
User u = new User(
Alias = 'lowpriv',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'LowPriv',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'lowpriv' + System.currentTimeMillis() + '@example.com'
);
insert u;
Boolean denied = false;
System.runAs(u) {
try {
AccountService.getAccounts();
} catch (QueryException e) {
denied = true;
}
}
System.assert(denied, 'Expected a QueryException for a user without Account access');
}
}The denied flag is set inside the block and checked after it. The assertion is outside runAs so a failure reports clearly.
Testing the positive case
A good suite also proves that an authorized user succeeds. Otherwise a service that always throws would pass the negative test. Create a second user with a profile or permission set that grants Account read access, then assert that the call returns records.
To grant access without changing the profile, assign a permission set to the user inside the test:
PermissionSet ps = [SELECT Id FROM PermissionSet WHERE Name = 'Account_Reader' LIMIT 1];
insert new PermissionSetAssignment(AssigneeId = u.Id, PermissionSetId = ps.Id);Here Account_Reader is a permission set in your own org or package. Replace the name with one that exists in yours.
Common mistakes
| Mistake | Effect | Fix |
|---|---|---|
| Asserting only on the happy path | Missing enforcement goes unnoticed | Add a negative test for each user mode call |
| Inserting the user inside `runAs` | The insert runs with the low-privilege user's access, which may fail | Insert the user before `runAs` |
| Hard-coding a duplicate `UserName` | Insert fails on uniqueness | Add `System.currentTimeMillis()` or a random suffix |
| Catching `Exception` broadly | A different error can pass the test | Catch `QueryException` or `DmlException` specifically |
| Depending on a standard profile name | Test fails in orgs where the profile is renamed or absent | Create users from a permission set you control |
Testing DML failures
DML in user mode throws a DmlException when the user lacks create access. With the partial-success overload, Database.insert(records, false, AccessLevel.USER_MODE) returns SaveResult objects instead. In that case, assert on isSuccess() and on the errors:
System.runAs(u) {
List<Database.SaveResult> results =
Database.insert(new List<Contact>{ new Contact(LastName = 'Test') }, false, AccessLevel.USER_MODE);
System.assert(!results[0].isSuccess(), 'Insert should be denied');
}Exercise
A test calls a service method that uses WITH USER_MODE, and it passes without any System.runAs. Why does that not prove enforcement, and what do you change?
Show answer
Without System.runAs, the query runs as the test runner, who usually has broad access, so the query succeeds even if enforcement were missing. Create a user with a low-privilege profile or permission set, insert it outside the block, call the method inside System.runAs, and assert that a QueryException is thrown. Add a second test with an authorized user to confirm the positive case.
Exercise
Why should the test user be inserted before the System.runAs block rather than inside it?
Show answer
Code inside System.runAs runs with the permissions of the low-privilege user, who may not be allowed to create User records. Inserting the user first, in the test's own context, avoids that failure.