Test class never runs a case as another user
ID |
apex.correctness.unit_test_runas |
Severity |
info |
Remediation Complexity |
medium |
Remediation Risk |
low |
Remediation Effort |
medium |
Resource |
Test Quality |
Language |
Apex |
Description
Reports an @IsTest class whose whole body never calls System.runAs, so every case in it executes in the system context.
Rationale
Apex tests run as a system user unless System.runAs says otherwise, and in that context object permissions, field-level security and sharing rules are simply not applied. A class that never changes user therefore proves nothing about the people who will actually run the code: the query returns rows the sales rep cannot see, the update succeeds on a field the profile has read-only, and the test stays green. The defect then arrives as a runtime INSUFFICIENT_ACCESS or a silently empty list in production, on a code path the coverage report claimed was tested.
The following code illustrates the pattern detected by this rule:
// FLAGGED: Test class never runs a case as another user
@IsTest
private class AccountShareServiceTest {
@TestSetup
static void setup() {
insert new Account(Name = 'Acme');
}
@IsTest
static void accountIsVisible() {
List<Account> found = [SELECT Id, Name FROM Account];
Assert.areEqual(1, found.size(), 'the setup account was expected');
}
}
Remediation
Wrap at least the permission-sensitive cases in a System.runAs(u) { … } block, with u created from the profile or permission set the feature is meant for. Combine it with Test.startTest()/Test.stopTest() so the assertions run under the same user, and keep a separate case for each profile whose access differs.