I wrote a test class. In test setup i am creating permissionSet and other custom object data. my test method would be like below,

  user = new user(values)
     insert permisisonset(...value...);
   insert customObject_c(..values...);
     permissionHandler.updatePermisionSet(); //Initially I got mixed DML error here. but above runaA(user) help me solved.

i checked the log. Its pointing to the original class (insert permissionsetList) mixed DML error. After that i added another runas in test method like below,

  System.runAs(new User(ID = UserInfo.getUserID()))
         permissionHandler.updatePermisionSet(); //working fine.

Its working. I am confused.. still its running in system context then why it got resolved by adding getUserID() in runAs context.

Any advise or comments.

1 Answer 1


Interesting question: you're using System.RunAs() to run exactly as the same user as before, right?

This documentation has some interesting information. After explaining the cause of the error, it says this (highlight is mine):

This restriction exists because some sObjects affect the user’s access to records in the org. You must insert or update these types of sObjects in a different transaction to prevent operations from happening with incorrect access-level permissions.

From the System.RunAs()documentation, we know that:

The system method runAs enables you to write test methods that change the user context to an existing user or a new user

and that:

The original system context is started again after all runAs test methods complete.

I'm assuming that, the moment you do System.Runas(User u), all the permissions of the user u are re-read form the database and re-applied to the running context. I guess that would be the reason why it works. But it's just an educated guess. Unfortunately, I don't have any further documentation to support that idea.

Interestingly enough, the both links above mentions using System.RunAs() as a workaround for the mixed DML error.

  • 2
    Using the runAs Method goes in further detail; you might consider adding this to your answer.
    – sfdcfox
    Dec 20, 2016 at 12:19
  • 1
    The use of system.runAs creates a new transaction.
    – Adrian Larson
    Dec 20, 2016 at 22:10

You must log in to answer this question.

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