Comprehensive and Detailed Explanation From Exact Extract:
By default, Apex tests run in a system context that does not respect sharing rules. However, the getAllAccounts method is defined in a with sharing class, so it does respect sharing rules. Therefore, to correctly simulate how a Standard User would see the data, the test must be run in the context of that user.
To do this, the developer should use System.runAs() to switch the test context to the Standard User, ensuring that sharing rules are enforced for the user running the test. This allows the test to correctly verify the data the user can access.
Example of Corrected Test Method:
apex
CopyEdit
@isTest
private static void getAllAccounts_StandardUser_Test() {
User standardUser = [SELECT Id FROM User WHERE Profile.Name = 'Standard User' AND UserName =
'
[email protected]' AND isActive = true LIMIT 1];
System.runAs(standardUser) {
List<Account> result = AccountsController.getAllAccounts();
System.assertEquals(20, result.size());
}
}
Reference:
Apex Testing Best Practices - Using runAs()