Sub topic 15
Testing Field Access with System.runAs
This chapter assumes you can write Apex tests with @IsTest, and that you know user-mode SOQL (WITH USER_MODE), Security.stripInaccessible, and how a permission set grants field access. By the end you should be able to write tests that prove your code respects field-level security (FLS) for a specific kind of user.
Why FLS needs its own tests
Apex tests run as the user who started the test run, usually an administrator. Administrators typically read and edit every field. If you write a test that queries a restricted field and asserts the query works, it passes for the wrong reason. The field was visible only because of who ran the test.
An FLS test must do three things:
- Create a user whose access is known and limited.
- Run the code under test as that user.
- Assert on the outcome: an exception, a stripped field, or a successful read.
What System.runAs does and does not do
System.runAs(user) runs a block of code in the context of another user. Inside the block, UserInfo.getUserId() returns that user. Record sharing is evaluated for that user in code declared with sharing.
System.runAs does not turn on FLS enforcement by itself. Plain Apex still runs in system mode, so a standard SELECT inside runAs returns restricted fields anyway. The test only proves something when the code under test uses an enforcement mechanism such as WITH USER_MODE, AccessLevel.USER_MODE, or stripInaccessible. runAs supplies the user, and the enforcement code decides what that user may see.
Building the test user
Choose a profile with minimal access, then add access through a permission set. This keeps the test close to how the field is granted in production. The examples below assume the field Account.Internal_Notes__c and a permission set named Account_Notes_Access that grants Read on it, as in the metadata chapter. Neither is part of a default org, so the tests fail until both exist.
@IsTest
private class AccountNotesFlsTest {
private static User createUser(Boolean withNotesAccess) {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
User u = new User(
Alias = 'flsusr',
Email = '[email protected]',
EmailEncodingKey = 'UTF-8',
LastName = 'FlsTester',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'flsusr' + System.currentTimeMillis() + '@example.com'
);
insert u;
if (withNotesAccess) {
PermissionSet ps = [
SELECT Id FROM PermissionSet
WHERE Name = 'Account_Notes_Access' LIMIT 1
];
insert new PermissionSetAssignment(
AssigneeId = u.Id,
PermissionSetId = ps.Id
);
}
return u;
}
@IsTest
static void userWithoutAccessCannotQueryField() {
User u = createUser(false);
Boolean blocked = false;
System.runAs(u) {
insert new Account(Name = 'Acme', Internal_Notes__c = 'Private');
try {
Database.query(
'SELECT Id, Internal_Notes__c FROM Account',
AccessLevel.USER_MODE
);
} catch (QueryException e) {
blocked = true;
}
}
Assert.isTrue(blocked, 'User mode should reject a field the user cannot read');
}
@IsTest
static void userWithPermissionSetCanQueryField() {
User u = createUser(true);
System.runAs(u) {
insert new Account(Name = 'Acme', Internal_Notes__c = 'Private');
List<Account> rows = Database.query(
'SELECT Id, Internal_Notes__c FROM Account',
AccessLevel.USER_MODE
);
Assert.areEqual(1, rows.size());
Assert.areEqual('Private', rows[0].get('Internal_Notes__c'));
}
}
}The inserts inside runAs are system-mode DML, so they succeed whatever the user's FLS is. That is intentional. The test is about reads, and the setup data must exist either way. The second test is the positive case. It proves the permission set is what opens access, and it guards against a negative test that passes because of a typo.
Testing stripInaccessible
Security.stripInaccessible does not throw when a field is hidden. It removes the field from the records and reports what it removed. Assert on both.
@IsTest
static void stripInaccessibleRemovesHiddenField() {
User u = createUser(false);
System.runAs(u) {
insert new Account(Name = 'Acme', Internal_Notes__c = 'Private');
List<Account> raw = [SELECT Id, Name, Internal_Notes__c FROM Account];
SObjectAccessDecision decision =
Security.stripInaccessible(AccessType.READABLE, raw);
List<Account> safe = (List<Account>) decision.getRecords();
Assert.isFalse(
safe[0].getPopulatedFieldsAsMap().containsKey('Internal_Notes__c'),
'The hidden field should be removed from the record'
);
Assert.isTrue(
decision.getRemovedFields().get('Account').contains('Internal_Notes__c'),
'The decision should report the removed field'
);
}
}Place this method inside the same test class as the earlier examples so it can call createUser.
Common errors
- Mixed DML error. Inserting a setup object (
User,PermissionSetAssignment) and a non-setup object (Account) in one transaction throwsMIXED_DML_OPERATION. The examples avoid it because the Account insert happens insideSystem.runAs, which starts a separate context. If you must insert records first, wrap the setup DML inSystem.runAs, or put the data in a@TestSetupmethod. - Testing as an administrator. A test with no
runAspasses for most fields. Always assert both the allowed and the denied path. - Expecting
runAsto enforce FLS. If the code under test uses a plainSELECT, it returns the hidden field and your "blocked" assertion fails. Fix the code, not the test. - Hard-coded permission set that does not exist. The
[SELECT ... LIMIT 1]fails with aQueryException("List has no rows for assignment") if the permission set is not deployed. Deploy the metadata with your code so tests can find it. - Profile names vary by org.
Standard Userexists in most orgs but can be renamed. In a shared codebase, consider a dedicated test profile deployed as metadata. - Unique usernames. Usernames must be unique across all Salesforce orgs. The timestamp suffix in the examples keeps repeated runs from colliding.
What to cover
| Scenario | Expected result |
|---|---|
| User with no field access, user-mode query | `QueryException` |
| User with Read access, user-mode query | Rows returned with the field |
| User with no access, `stripInaccessible` | Field removed, listed in `getRemovedFields()` |
| User with Read only, user-mode update of the field | Failure; test it in your org to confirm the exception type before asserting on it |
Exercise
Your test uses System.runAs(limitedUser) and runs a plain SOQL query that selects a field the user cannot read. The test expects an exception but none is thrown. Why, and what are two ways to fix the code under test?
Show answer
System.runAs changes the running user and applies record sharing, but it does not enforce FLS. A plain SOQL query runs in system mode and returns the field. Fix the code by adding WITH USERMODE to the query (or using Database.query with AccessLevel.USERMODE), or by passing the results through Security.stripInaccessible(AccessType.READABLE, records).
Exercise
A test inserts a User and then, in the same test method outside any runAs block, inserts an Account. It fails with MIXEDDMLOPERATION. Give two ways to fix it.
Show answer
Wrap the User insert (or the Account insert) in System.runAs so it runs in a separate context, or move the data creation into a @TestSetup method, which runs in its own transaction.