[SalesForce] Use runAs to unit test class without ‘with sharing’ keyword

There is class without 'with sharing' to ignore sharing and delete sobject in system context.

I am writing unit test to verify the behavior that execution of this code will definitely delete this sobject for any user. This sobject has sharing rules based on role. sharing rule+'with sharing' doesn't allow to delete objects but when we run in system apex context without 'with sharing' we can delete(because it is system context) and it is ok based on the requirement.

When I try to test this code from UI, it behaves as expected – sobject is deleted.

When I run this code with system.runAs in unit test by setting target user with target role to apply sharing rule, there is access permission exception and sobject is not deleted.
Does system.runAs enforce sharing and tested apex code is not in system context being in test context?

Best Answer

If the Test class is defined with keyword "with sharing" then all sharing rules/permissions will be enforced to that class and it will behave according to sharing applied to the test running context user.

Any apex class which have "with sharing" keyword, will have to follow all sharing settings. Otherwise Apex class run in System mode by default.

However, in most cases test class are executed by "System Administrator" which have highest level of permissions. If you setting a runAs() then profile level permission will be applied to that user as well as sharing permissions in union with permission available to context user.

Related Topic