I know we can share records programmatically via Apex.

We can also check CRUD permissions on an object.

But, can we use Apex to modify object-level CRUD permissions?

I don't think so (as this would allow a crafty developer to bypass the sysadmin's settings), but I just wanted confirmation of this.

To give you some context, this is just for unit testing how one of our components behaves when an object cannot be viewed. We'd like to temporarily remove access to some objects for a profile during a test, and ensure that our controller behaves correctly.

  • Removing access? Probably not. You might be able to increase it using ObjectPermissions, though I've never performed DML on it.
    – Adrian Larson
    Feb 10, 2016 at 15:21
  • Why don't you just identify a profile with less permissions to test against?
    – Adrian Larson
    Feb 10, 2016 at 15:22
  • @AdrianLarson that could be a solution, as long as it's an out-of-the box profile. Will try. What I don't want to do is having to create custom profiles just to get a unit test to work. Thanks!
    – mkorman
    Feb 10, 2016 at 15:29

2 Answers 2


If you have a Profile with lower permissions already, I would take that approach. Typically I will do something like:

    // do stuff

Salesforce makes it difficult to reduce permissions, it's more of a lock things down and then open them up system.


Well, you cant change or update profiles directly from Apex.

You should run test as a user, which doesnt have access to these objects.

  Profile p = [SELECT Id FROM Profile WHERE Name='Standard User']; 
  User u = 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='[email protected]');

  System.runAs(u) {
     // The following code runs as user 'u' 
     System.debug('Current User: ' + UserInfo.getUserName());
     System.debug('Current Profile: ' + UserInfo.getProfileId()); 
  • Ha, we must have been writing these up at the same time.
    – Adrian Larson
    Feb 10, 2016 at 15:38
  • Thanks for the response. Very similar to the one that @AdrianLarson wrote.
    – mkorman
    Feb 10, 2016 at 15:38
  • Yeah! :) Enjoy your reputation points :D Feb 10, 2016 at 15:40
  • 1
    Hey, I upvoted both of you ;)
    – mkorman
    Feb 10, 2016 at 15:49

You must log in to answer this question.

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