My class is using with sharing
keyword and method has a query on object which system admin only has access.
List<Login__c> recList = [select id, clientId__c, clientsecret__c from login__c];
So in my test class to test for multiple profiles I am using below:
User u = [select id from user where profile.name != 'System Administrator' Limit 1];
system.runAs(u) {
MainClass.retrieveQuery();
}
I expect above to throw error when method is called as query in that method can only be run succesfully by system admin but it doesnot throw any error.
However, if I pass specific profile name which is not system admin as below, it runs as expected throws an exception "List has no rows for assignment to sObject"
User u = [select id from user where profile.name = 'Integration User' Limit 1];
system.runAs(u) {
MainClass.retrieveQuery();
}
My another question is how to catch list has no exceptions error. I tried below:
List<Login__c> recList = new List<Login__c>();
try {
recList = [select id, clientId__c, clientsecret__c from login__c];
} catch(QueryException qe) {
system.debug('Query exception: '+qe);
} catch(Exception e) {
system.debug('Exception: '+e);
}
Even though above code throws exception "List has no rows exception" when run by non-system admin profile, this exception is not caught in either catch block.
IsActive = true
; (2)recList = [select id, clientId__c, clientsecret__c from login__c];
will never throw query has no rows exception; it will return 0 rows[select id from user where profile.name = 'Integration User' Limit 1];
does not return any user so the exception where asselect id from user where profile.name != 'System Administrator' Limit 1
returns a value so no exception. Nothing to do withsystem.runAs
orwith sharing
keyword here.