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?

  • 4
    Can you explicitly add the without sharing keyword and try? My hunch is you're using the with sharing keyword in the test class..
    – Sam
    Commented Feb 11, 2015 at 7:29
  • @theGreatDanton, thank you so much! explicitly setting 'without sharing' has fixed the issue. I thought that class with empty modifier behaves the same as with 'without sharing' - in system context. But in this case when I remove 'without sharing', it fails. So 'without sharing' did the trick. Thanks a lot! Could you please post this answer so I can accept it.
    – Natallia
    Commented Feb 11, 2015 at 22:06

1 Answer 1


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.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .