Consider the following code snippet:
Java
01 public with sharing class AccountsController{
03 @AuraEnabled
04 public List
05 return [Select Id, Name, Industry FROM Account];
06 }
08 }
As part of the deployment cycle, a developer creates the following test class:
Java
@isTest
private class AccountsController_Test{
@TestSetup
private static void makeData(){
User user1 = [Select Id FROM User WHERE Profile.Name = 'System Administrator' ... LIMIT 1];
User user2 = [Select Id FROM User WHERE Profile.Name = 'Standard User' ... LIMIT 1];
TestUtils.insertAccounts(10,user1.Id);
TestUtils.insertAccounts(20,user2.Id);
}
@isTest
private static void testGetAllAccounts(){
// Query the Standard User into memory
List
System.assertEquals(20,result.size());
}
}
When the test class runs, the assertion fails. Which change should the developer implement in the Apex test method to ensure the test method executes successfully?
The failure of the assertion is caused by the with sharing keyword used in the AccountsController class and the context in which the test is running. The with sharing keyword enforces the sharing rules of the current user. In a test context, the code defaults to running as a System Administrator unless otherwise specified.
In the @TestSetup method, the developer created 10 accounts owned by a System Admin (user1) and 20 accounts owned by a Standard User (user2). When AccountsController.getAllAccounts() is called without a specific user context, it runs as the Admin and returns all 30 records. The assertion expects exactly 20 records (System.assertEquals(20, result.size())), which corresponds to the number of records owned by the Standard User.
To make the test pass, the developer must execute the method within the context of the Standard User. By querying user2 and using System.runAs(user2) (Option C), the sharing rules are enforced according to that user's perspective. Under with sharing, the Standard User will only 'see' the 20 account records they own (assuming a Private OWD and no other sharing rules apply), thus satisfying the assertion. Option A is incorrect as seeAllData=true bypasses the test isolation. Option D would result in a count of 30 (or 10 if restricted), which still fails the assertion.
Currently there are no comments in this discussion, be the first to comment!