System method runAs enables you to write test methods that change the user context to an existing user or a new user so that the user’s record sharing is enforced. The runAs method doesn’t enforce user permissions or field-level permissions, only record sharing.
Giving permission on object in profile comes under object sharing and runAs only consider record sharing.
Example Code:
@isTest
private class testSEClass{
private static testmethod void testSEClass(){
List<User> users = new List<User>();
Profile p = [SELECT Id FROM Profile WHERE Name like :'%' + 'std user clone' + '%' Limit 1];
for (Integer k = 0; k < 50; k++) {
users.add(new User(Alias = 'standt', Email = '[email protected]',
EmailEncodingKey = 'UTF-8', LastName = 'Testing', LanguageLocaleKey = 'en_US',
LocaleSidKey = 'en_US', ProfileId = p.Id, TimeZoneSidKey = 'America/Los_Angeles',
UserName = 'standarduser' + Math.random() + '@testorg.com'));
}
insert users;
System.runAs(users[0]) {
//This debug statement returns False.
System.debug(Account.sObjectType.getDescribe().isAccessible());
Account a = new Account(name='abcdsss');
insert a;
//It successfully inserts account record.
System.debug(a.id);
}
}
}
I tried this code in with sharing mode as well, i got same results. You can externally apply DML checks to check whether any user has object and field level permissions or not.
Resource