I'm getting DML errors when trying to test some triggers:

This error occurred: MIXED_DML_OPERATION: DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa).

I'm running my test case on a dev sandbox, and am inserting users before I insert a custom object. From my understanding, this is what is causing these MIXED_DML_OPERATION errors, as I'm updating configuration and standard objects in the same transaction.

That being said, is a single APEX test considered a transaction? Other than making changes to my code to account for testing, is there a way around inserting users in a test other than having seeAllData=true?

  • You can get around the mixed DML using system.runAs() Use SOQL to query for the Id of a single user with the System Administrator profile (you can do this without seeAllData=true). Using that User.Id you can then leverage a block of code preceded by the system.runAs(<user.Id>) method to insert your test Users. – John Thompson Feb 19 '18 at 22:36
  • don't even think about seeAllData=true – cropredy Feb 20 '18 at 1:08

First of all, you do not need to set SeeAllData=true if you want to see User records in a test. You always see them. Second of all, as outlined here the standard workaround to create a separate transaction inside your test method is to use system.runAs(user).

system.runAs(new User(Id=UserInfo.getUserId())
    // separate transaction

In an actual test, that would look something like:

static void testSomeStuff()
    User admin = [
        SELECT Id FROM User
        WHERE Profile.Name = 'System Administrator'
        LIMIT 1
    // it is a good idea to query for a privileged user
    // so the test will work no matter who runs it

        // insert users here
        // along with any other setup data

    // insert non setup objects

        // do stuff

    // verify behavior using assertions
|improve this answer|||||

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.