Sub topic 13
Testing sharing behavior
This chapter shows how to write Apex tests that prove a class respects, or deliberately bypasses, record-level sharing. It assumes you can write basic Apex test classes with @IsTest and @TestSetup. It also assumes you know how with sharing, without sharing, and inherited sharing behave, and how organization-wide defaults (OWD) control record visibility.
Why sharing needs its own tests
Sharing bugs hide easily. A developer who tests as an administrator sees every record, so a missing with sharing never shows up. The code works in the sandbox and leaks data in production. A test that only checks "the query returns an account" proves nothing about sharing.
A useful sharing test does three things:
- It creates a record the test user should not be able to see.
- It runs the code under test as that user.
- It asserts on how many records come back, or what happens on DML.
How test context works
Test methods run in system context as the user who started the test run. That user is often an administrator. Sharing is not applied to the test method itself, and the keyword on the test class does not make your assertions meaningful.
System.runAs(user) changes the user context for a block of code. Inside the block, classes declared with sharing apply that user's record access. runAs has limits:
| Aspect | Enforced inside `System.runAs`? |
|---|---|
| Record-level sharing for `with sharing` code | Yes |
| Object permissions (CRUD) in default system-mode code | No |
| Field-level security in default system-mode code | No |
| `WITH USER_MODE` and `AccessLevel.USER_MODE` checks | Yes, against the `runAs` user |
| Sharing for `without sharing` code | No, by design |
Because runAs does not enforce CRUD or field-level security (FLS) for ordinary code, you cannot show that a class respects those permissions by calling it inside runAs. You prove that with user-mode operations, covered later in this chapter.
The test design
The diagram shows the structure used in the rest of the chapter.
Building the test data
Creating a User and a record such as an Account in one transaction can raise a MIXED_DML_OPERATION error. Insert the users inside a System.runAs block that uses the current user. Then insert the record while running as the owner, so the owner owns it.
The test relies on the Account OWD being Private. If your org uses Public Read Only, the viewer can see the record and the test fails. The precondition assertion in the next example catches this and tells you why.
Testing the keyword on a class
This test class checks AccountRepository, the inherited sharing class from earlier in the tutorial. It calls the class from two inner callers that declare their sharing mode explicitly. That makes the call chain visible, and it does not depend on how a test method counts as an entry point.
@IsTest
private class AccountRepositoryTest {
private with sharing class SharingCaller {
public List<Account> find(String name) {
return AccountRepository.findByName(name);
}
}
private without sharing class SystemCaller {
public List<Account> find(String name) {
return AccountRepository.findByName(name);
}
}
private static final String ACCOUNT_NAME = 'Sharing Test Acct';
private static User buildUser(String alias) {
Profile p = [SELECT Id FROM Profile WHERE Name = 'Standard User' LIMIT 1];
return new User(
Alias = alias,
Email = alias + '@example.com',
EmailEncodingKey = 'UTF-8',
LastName = 'Tester' + alias,
LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US',
ProfileId = p.Id,
TimeZoneSidKey = 'America/Los_Angeles',
UserName = alias + Math.abs(Crypto.getRandomInteger()) + '@example.com.test'
);
}
private static User userByAlias(String alias) {
return [SELECT Id FROM User WHERE Alias = :alias LIMIT 1];
}
@TestSetup
static void setup() {
User owner = buildUser('shOwner');
User viewer = buildUser('shViewer');
System.runAs(new User(Id = UserInfo.getUserId())) {
insert new List<User>{ owner, viewer };
}
System.runAs(owner) {
insert new Account(Name = ACCOUNT_NAME);
}
}
private static void assertViewerCannotReadAccount(User viewer) {
Account acc = [SELECT Id FROM Account WHERE Name = :ACCOUNT_NAME LIMIT 1];
UserRecordAccess access = [
SELECT RecordId, HasReadAccess
FROM UserRecordAccess
WHERE UserId = :viewer.Id AND RecordId = :acc.Id
];
Assert.isFalse(
access.HasReadAccess,
'This test needs the Account org-wide default to be Private.'
);
}
@IsTest
static void withSharingHidesOtherUsersRecords() {
User viewer = userByAlias('shViewer');
System.runAs(viewer) {
assertViewerCannotReadAccount(viewer);
List<Account> result = new SharingCaller().find(ACCOUNT_NAME);
Assert.areEqual(0, result.size(), 'with sharing caller should see no records');
}
}
@IsTest
static void withoutSharingCallerSeesTheRecord() {
User viewer = userByAlias('shViewer');
System.runAs(viewer) {
assertViewerCannotReadAccount(viewer);
List<Account> result = new SystemCaller().find(ACCOUNT_NAME);
Assert.areEqual(1, result.size(), 'without sharing caller bypasses record sharing');
}
}
@IsTest
static void ownerSeesOwnRecordUnderSharing() {
User owner = userByAlias('shOwner');
System.runAs(owner) {
List<Account> result = new SharingCaller().find(ACCOUNT_NAME);
Assert.areEqual(1, result.size(), 'owner should see own record');
}
}
}Each test has a job:
- The first test proves the
inherited sharingclass enforces sharing when awith sharingclass calls it. - The second proves it does not enforce sharing when a
without sharingclass calls it. This confirms the inheritance behavior. - The third is a control. If the owner cannot see their own record, the other two results mean nothing.
The UserRecordAccess query is the precondition check. If the data does not match your assumptions, the test fails with a message that names the cause. Without it, you would get a confusing count mismatch.
Testing a class with a fixed keyword
For a class declared with sharing, the test is shorter. Run as the viewer, call the class directly, and assert on the count. Add one test as the owner to prove the positive case.
For a without sharing class, assert that the viewer still gets the record. That test documents that the bypass is intentional. If someone later changes the keyword, the test fails and the change gets reviewed.
Testing sharing through grants
Sharing also works the other way: a user gains access through a share record. You can test that a grant takes effect by creating an AccountShare row and checking that the with sharing result changes.
@IsTest
private class AccountShareGrantTest {
@IsTest
static void manualShareMakesRecordVisible() {
User owner = [SELECT Id FROM User WHERE Alias = 'shOwner' LIMIT 1];
User viewer = [SELECT Id FROM User WHERE Alias = 'shViewer' LIMIT 1];
Account acc = [SELECT Id FROM Account WHERE Name = 'Sharing Test Acct' LIMIT 1];
insert new AccountShare(
AccountId = acc.Id,
UserOrGroupId = viewer.Id,
AccountAccessLevel = 'Read',
OpportunityAccessLevel = 'None',
CaseAccessLevel = 'None',
RowCause = 'Manual'
);
System.runAs(viewer) {
List<Account> result = AccountRepository.findByName('Sharing Test Acct');
Assert.areEqual(1, result.size(), 'Shared record should now be visible');
}
}
}This class assumes the users and the account come from a @TestSetup method like the one above. A test class has its own setup data, so in practice you would add the same @TestSetup method here or move the shared builders into a test utility class. Here the viewer calls AccountRepository directly from runAs, so the test method is the entry point and the class runs with sharing. That makes the call-chain mode depend on the platform's entry-point rule, so prefer explicit callers when you need certainty.
Testing permission enforcement
runAs does not enforce CRUD or FLS for ordinary code, so a plain runAs test cannot prove a class respects them. User-mode operations do honor the runAs user. To test ContactService from earlier in the tutorial:
- Create a user whose profile or permission set lacks read access to a field, such as
Contact.Email. - Call
ContactService.getContacts()insideSystem.runAsfor that user. - Assert that a
QueryExceptionis thrown.
Also add a positive test with a fully permitted user, so you know the exception comes from the permission and not from a bug.
Common mistakes in sharing tests
- Testing only as an administrator. Administrators typically see all data, so every keyword appears to work.
- Not setting up a precondition. If the OWD is not Private, a "hidden record" test fails or passes for the wrong reason. Assert the user's access first.
- Forgetting the control test. Always check that the owner sees the record, so a zero count means "sharing hid it" and not "the data was never created".
- Using
SeeAllData=true. It makes results depend on whatever data exists in the org. Create your own records instead. - Expecting
runAsto enforce FLS. It enforces record sharing only. Use user-mode SOQL and DML to test permissions. - Mixed DML errors. Insert users inside a
System.runAsblock, as shown in the setup method.
Exercise
A developer writes a test that inserts an Account as an administrator, then calls a with sharing class directly (not inside System.runAs) and asserts that one record is returned. The test passes. Why is the test not proof that the class respects sharing, and what two changes make it meaningful?
Show answer
Outside System.runAs, the running user is typically an administrator who can see every record, so the query returns the record whatever the keyword is. First, create a second user and run the call inside System.runAs(thatUser), with a record that user cannot see, then assert zero records are returned. Second, add a precondition (for example a UserRecordAccess check) and a control test as the owner, so the zero result is known to come from sharing.