Sub topic 13
Testing sharing behavior
This chapter assumes you can write Apex test classes with @IsTest. It also assumes you know the with sharing and without sharing keywords from earlier chapters, and that you know the org-wide default (OWD) for the object you test.
Why tests need extra setup
Test methods run in system context, like the rest of Apex. If a test calls a with sharing class directly, the class applies the sharing of the user who runs the test. That is usually an administrator who sees every record. The test passes, but it proves nothing about sharing.
To test sharing, run the code as another user with System.runAs(). Inside the block, record-level sharing is applied for that user.
A worked test
This test uses AccountReader (with sharing) and AccountAdminReader (without sharing) from earlier in the tutorial. It assumes the Account OWD is Private. If your org uses Public Read Only or Public Read/Write, the second user can see the record and the first assertion fails.
@IsTest
private class AccountSharingTest {
private static User makeUser(String alias) {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
return new User(
Alias = alias,
LastName = alias,
Email = alias + '@example.com',
Username = alias + System.currentTimeMillis() + '@example.com.test',
ProfileId = p.Id,
EmailEncodingKey = 'UTF-8',
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
TimeZoneSidKey = 'America/Los_Angeles'
);
}
@IsTest
static void withSharingHidesRecordsOwnedByOthers() {
User owner = makeUser('owner1');
User other = makeUser('other1');
insert new List<User>{ owner, other };
System.runAs(owner) {
insert new Account(Name = 'Private Co');
}
System.runAs(other) {
Assert.areEqual(0, AccountReader.getAccounts().size(),
'with sharing should hide the private account');
Assert.areEqual(1, AccountAdminReader.getAllAccounts().size(),
'without sharing should return it');
}
}
}The counts are exact because tests do not see existing org data unless you use @IsTest(SeeAllData=true). Avoid that setting.
Three details matter here:
- The account is inserted inside
System.runAs(owner). That makesownerthe record owner. It also avoids aMIXED_DML_OPERATIONerror, which Salesforce raises when one transaction changes a setup object such asUserand a normal object such asAccount. - The test asserts on both keywords. The
without sharingassertion confirms the bypass is real and not an accident of the test data. - Usernames must be unique across all Salesforce orgs, so the example appends a timestamp.
Testing inherited sharing
An inherited sharing class has no mode of its own, so test it from two callers. Call it from a with sharing wrapper and from a without sharing wrapper. Define both as private inner test classes and assert that the results differ. Also call it directly inside runAs. An entry point runs with sharing, so the direct call should behave like with sharing.
Common test mistakes
| Mistake | Effect | Fix |
|---|---|---|
| No `runAs` | Test runs as an admin who sees everything | Wrap the call in `System.runAs(user)` |
| Owner and tester are the same user | Record is always visible | Create the record as a different user |
| Wrong OWD assumption | Test passes or fails depending on the org | State the OWD in a comment, or share records explicitly |
| Only the `with sharing` case is asserted | A class that silently lost its keyword goes unnoticed | Assert the `without sharing` and `inherited sharing` cases too |
Exercise
A test inserts an Account as the running admin, then calls a with sharing method that queries Accounts, and asserts one row comes back. Why does this test not prove the class enforces sharing, and what two changes fix it?
Show answer
The admin owns the record and can see all records, so the query returns the row even if sharing were not applied. Create the account inside System.runAs() as one user, then call the method inside System.runAs() as a different user, with the OWD set to Private. Then assert that the query returns zero rows.