Testing sharing requires running tests as different users.
`System.runAs()`:
`apex @isTest static void testSharingForSalesUser() { // Setup data as System Admin (not in runAs) Account a = new Account(Name='Sales-Owned'); a.OwnerId = createSalesUser().Id; insert a;
// Now run as a different user User otherSalesUser = createSalesUser(); System.runAs(otherSalesUser) { // What does this user see? List<Account> visible = [SELECT Id FROM Account]; System.assert(visible.isEmpty() || !visible[0].Id.equals(a.Id), 'Other Sales User should NOT see private Account'); } } `
Patterns:
1. Create test users with specific profiles / permission sets.
apex private static User createSalesUser() { Profile p = [SELECT Id FROM Profile WHERE Name='Sales Rep']; User u = new User( Username='test'+System.now().getTime()+'@example.com', Email='test@example.com', FirstName='Test', LastName='Sales', ProfileId=p.Id, Alias='tsls', TimeZoneSidKey='America/New_York', LocaleSidKey='en_US', EmailEncodingKey='UTF-8', LanguageLocaleKey='en_US' ); insert u; return u; }
2. Run code as that user via `System.runAs(user) { ... }`.
3. Assert what they can / can't see.
Test scenarios:
- OWD enforcement: with Private OWD, owner sees, non-owner doesn't.
- Role hierarchy: manager sees subordinate's records.
- Sharing rule grants: criteria-based access works.
- Manual sharing: per-record share works.
- Apex Managed Sharing: programmatic shares work.
- External user access: HVPU, Sharing Sets.
Common pitfalls:
- Tests run as System Admin — doesn't catch sharing issues.
- No `System.runAs` — tests don't validate sharing.
- Ignoring user setup — test users must have appropriate profiles.
Senior QA insight: sharing tests catch security regressions. Most sharing bugs surface in production because tests didn't run as right user.
The senior framing: `System.runAs` is the security-testing tool. Use deliberately for any sharing-sensitive code.
Permission tests follow same pattern: create user with specific permission set; runAs them; assert they can/can't do what they should/shouldn't.
