Sub topic 9
Testing enforcement with System.runAs
This chapter assumes you can read basic Apex and SOQL and know how profiles and permission sets grant object permissions (CRUD) and field-level security (FLS). It also assumes you have written an Apex test class with @IsTest methods. You will learn how to prove that your user mode code denies access when it should, and allows it when it should.
Why tests need runAs
Apex tests run in system mode, like all Apex. The user context is the person who started the test run, usually an administrator with broad access. A user mode query run by that person almost always succeeds, so a test without System.runAs proves nothing about enforcement.
Consider the AccountService.getAccounts() method from earlier in this tutorial, which uses WITH USER_MODE. If you call it from a plain test as an administrator, it returns rows. The test passes. It would still pass if someone removed WITH USER_MODE from the query.
System.runAs(user) runs a block of code as another user. Inside the block, user mode operations check that user's permissions. Your test then asserts the outcome you expect.
What runAs changes and what it does not
| Behavior | Inside `System.runAs` |
|---|---|
| User mode SOQL and DML (`WITH USER_MODE`, `as user`, `AccessLevel.USER_MODE`) | Checks the permissions of the `runAs` user |
| Classes declared `with sharing` | Apply the `runAs` user's sharing access |
| `UserInfo.getUserId()` | Returns the `runAs` user's Id |
| Code in system mode (no user mode keyword) | Still ignores object permissions and FLS |
| Governor limits | Not reset. `Test.startTest()` does that |
The fourth row is a common source of false confidence. System.runAs does not turn on CRUD or FLS enforcement. It only changes who the user is. Code that runs in system mode still ignores that user's CRUD and FLS inside the block. You test enforcement by combining runAs with code that actually uses user mode.
Building test users with exact permissions
To test a boundary, you need a user who has some permissions and lacks others. The cleanest approach is a minimal profile plus a permission set you create in the test. Creating the permission set in the test keeps the test independent of whatever your org's real permission sets contain.
@IsTest
public class TestUserFactory {
public static User createMinimalUser(String alias) {
Profile p = [
SELECT Id FROM Profile
WHERE Name = 'Minimum Access - Salesforce'
LIMIT 1
];
User u = new User(
Alias = alias,
Email = alias + '@example.com',
EmailEncodingKey = 'UTF-8',
LastName = alias,
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = alias + System.currentTimeMillis() + '@example.com'
);
insert u;
return u;
}
public static void grant(
User u,
String objectName,
Boolean canRead,
Boolean canCreate,
List<String> readableFields
) {
PermissionSet ps = new PermissionSet(
Label = 'Test ' + objectName + ' ' + u.Alias,
Name = 'Test_' + objectName + '_' + u.Alias
);
insert ps;
insert new ObjectPermissions(
ParentId = ps.Id,
SobjectType = objectName,
PermissionsRead = canRead,
PermissionsCreate = canCreate
);
List<FieldPermissions> fieldPerms = new List<FieldPermissions>();
for (String fieldName : readableFields) {
fieldPerms.add(new FieldPermissions(
ParentId = ps.Id,
SobjectType = objectName,
Field = objectName + '.' + fieldName,
PermissionsRead = true,
PermissionsEdit = false
));
}
insert fieldPerms;
insert new PermissionSetAssignment(
AssigneeId = u.Id,
PermissionSetId = ps.Id
);
}
}A few details about this helper:
- Each user needs a distinct alias of eight characters or fewer, because the alias is part of the permission set's unique
Name. - A permission set that grants create must also grant read on the same object, so the helper's
canCreatecalls should passcanRead = true. - The profile
Minimum Access - Salesforceexists in most orgs but is not guaranteed. If your org or scratch org definition lacks it, query a profile you know exists. Do not hard-code a profile Id. User,PermissionSet,ObjectPermissions,FieldPermissions, andPermissionSetAssignmentare all setup objects. This matters in the next section.
Test 1: no object access
This test checks the case where the user has no Account read permission at all. It uses the getAccounts() method shown earlier in this tutorial.
@IsTest
private class AccountServiceTest {
@TestSetup
static void makeData() {
insert new Account(Name = 'Acme', Industry = 'Energy');
}
@IsTest
static void queryFailsWithoutAccountAccess() {
User u = TestUserFactory.createMinimalUser('noacct');
Boolean denied = false;
System.runAs(u) {
try {
AccountService.getAccounts();
} catch (QueryException e) {
denied = true;
}
}
Assert.isTrue(denied, 'Expected a QueryException for a user without Account access');
}
}The denied flag is declared outside the block because the assertion should run as the original test user. Running assertions inside runAs works, but keeping them outside avoids confusion about whose context you are in.
There is a common mistake with the try/catch pattern. If you write try { call(); Assert.fail('...'); } catch (Exception e) { ... }, then the AssertException thrown by Assert.fail is itself caught by your broad catch. Catch the specific exception type (QueryException), or use a boolean flag as above, so a missing exception cannot hide.
Test 2: field-level security
An object permission alone does not make the query pass. getAccounts() selects Industry and filters on it, so the user needs read access to that field. This test grants Account read but no field permissions, and then a second test grants the field.
@IsTest
static void queryFailsWithoutIndustryFieldAccess() {
User u = TestUserFactory.createMinimalUser('nofield');
TestUserFactory.grant(u, 'Account', true, false, new List<String>());
Boolean denied = false;
System.runAs(u) {
try {
AccountService.getAccounts();
} catch (QueryException e) {
denied = true;
}
}
Assert.isTrue(denied, 'Expected a QueryException because Industry is not readable');
}
@IsTest
static void querySucceedsWithObjectAndFieldAccess() {
User u = TestUserFactory.createMinimalUser('canread');
TestUserFactory.grant(u, 'Account', true, false, new List<String>{ 'Industry' });
List<Account> result;
System.runAs(u) {
result = AccountService.getAccounts();
}
Assert.areEqual(1, result.size(), 'User should see the account from test setup');
Assert.areEqual('Energy', result[0].Industry);
}Add both methods to AccountServiceTest. The pair is the important pattern. A denial test alone passes if the code is broken in a way that always throws. A matching success test shows the code works when permissions are present, so together the two prove the permission is the deciding factor.
The success test also depends on record sharing. The user sees the account only if the org-wide default or a sharing rule lets them. If your Account default is Private, a user with read permission but no sharing access gets an empty list, not an exception. That is a different failure and a different test. To test it, assert result.isEmpty() for a user without sharing access, and use a with sharing class so sharing applies.
Test 3: DML in user mode
DML failures follow the same structure. Here the ContactService class from the DML chapter is tested with a user who lacks Contact create permission.
@IsTest
private class ContactServiceTest {
@IsTest
static void insertFailsWithoutCreatePermission() {
User u = TestUserFactory.createMinimalUser('nocreate');
Boolean denied = false;
System.runAs(u) {
try {
ContactService.createContact('Smith', '[email protected]');
} catch (DmlException e) {
denied = true;
}
}
Assert.isTrue(denied, 'Expected a DmlException without Contact create access');
}
@IsTest
static void partialSaveReportsErrorsPerRecord() {
User u = TestUserFactory.createMinimalUser('partial');
List<Database.SaveResult> results;
System.runAs(u) {
results = ContactService.createContacts(
new List<Contact>{ new Contact(LastName = 'Jones') }
);
}
Assert.isFalse(results[0].isSuccess(), 'The insert should fail for this user');
Assert.isFalse(results[0].getErrors().isEmpty());
}
}The two methods show the two failure shapes. insert as user throws, so you catch a DmlException. Database.insert(contacts, false, AccessLevel.USER_MODE) does not throw for per-record failures, so you inspect each SaveResult. Your tests should match whichever style the code under test uses.
Which exception to expect
| Operation | Failure signal in tests |
|---|---|
| Static SOQL with `WITH USER_MODE` | `QueryException` |
| `Database.queryWithBinds(..., AccessLevel.USER_MODE)` | `QueryException` |
| `insert as user` and other DML keywords | `DmlException` |
| `Database.insert(records, false, AccessLevel.USER_MODE)` | No exception. `SaveResult.isSuccess()` is false |
| `Security.stripInaccessible` | No exception. Inaccessible fields are removed from the records |
If you are unsure what a particular operation throws in your org's API version, write a quick failing test and print e.getTypeName() and e.getMessage(), then pin the assertion to the type you observed.
Practical advice
- Test both directions. For each permission, write one test where it is missing and one where it is present.
- Grant only what the scenario needs. Starting from the minimal profile and adding one permission at a time makes each test show which permission matters.
- Assert on behavior, not just that no exception occurred. A success test should check the returned records, the fields populated, or the rows inserted.
- Keep user creation in a helper. Duplicated user setup code makes tests long and hides the permission under test.
- Do not rely on real permission sets. Tests that assign an org's production permission sets break when an admin edits them.
- If you use
Security.stripInaccessible, test it withrunAstoo. Assert that the inaccessible field is absent by callingrecord.isSet('Industry')or by catchingSObjectExceptionwhen reading it.
Exercise
A developer writes a test that calls AccountService.getAccounts() directly with no System.runAs. The test asserts that the result is not empty and passes. The team concludes that WITH USER_MODE is working. What is wrong with that conclusion, and what two tests would you add?
Show answer
The test runs as the user who started the test run, usually an administrator, so the query succeeds regardless of whether WITH USER_MODE is present. It proves nothing about enforcement. Add a denial test that creates a user without Account read access, calls getAccounts() inside System.runAs, and asserts that a QueryException is thrown. Add a matching success test that grants Account read and the Industry field, calls the method inside System.runAs, and asserts that the expected account is returned.
Exercise
Your test creates a user and a permission set, then inserts an Account in the same test method, and the test fails with MIXED_DML_OPERATION. Give two ways to fix it.
Show answer
Move the Account insert into a @TestSetup method so it runs in its own transaction. Alternatively, wrap the setup-object DML (user, permission set, assignment) in a System.runAs block so it runs in a separate context from the Account insert.