First of all, it does not appear necessary to query the User
record based on what you have posted. You can change your Account
query to just:
public static List<Account> getAllAccounts()
{
return [SELECT Name FROM Account WHERE OwnerId = :UserInfo.getUserId()];
}
Secondly, you just need to set up a User
in your test and then create Account
records they own. It will be easier to test this functionality if you have a method that just returns the query results, then put any further processing logic in a different method.
static testMethod void testGetAllAccounts()
{
User testUser = new User(/*required fields*/);
insert testUser;
final Integer recordCount = Limits.getLimitQueries() + 1;
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < recordCount; i++)
{
accounts.add(new Account(OwnerId=testUser.Id/*, requiredFields*/));
}
insert accounts;
List<Account> allAccounts;
system.runAs(testUser)
{
Test.startTest();
allAccounts = MyClass.getAllAccounts();
Test.stopTest();
}
system.assertEquals(recordCount, allAccounts.size(),
'All accounts pertaining to this user should be found);
}
You can add a separate test identical to the above, but set OwnerId=UserInfo.getUserId()
, and assertEquals(0, allAccounts.size())
. In other words, the query should not find Account
records where the OwnerId
is not the running user.