How to avoid MIXED_DML_OPERATION error in Salesforce tests that create Users

Not many Salesforce people on here yet, I guess.

I found a solution, I don’t know why it works, but it works.

All parts of the test that access normal objects need to be wrapped in a System.runAs that explicitly uses the current user, like this:

User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
System.runAs ( thisUser ) {
    // put test setup code in here
}

So, the example text_mixed_dmlbug method given in the question, would become:

static testMethod void test_mixed_dmlbug() {  
    User u;
    Account a;      
    User thisUser = [ select Id from User where Id = :UserInfo.getUserId() ];
    System.runAs ( thisUser ) {
        Profile p = [select id from profile where name="(some profile)"];
        UserRole r = [Select id from userrole where name="(some role)"];
        u = new User(alias="standt", email="[email protected]", 
            emailencodingkey='UTF-8', lastname="Testing", 
            languagelocalekey='en_US', 
            localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
            timezonesidkey='America/Los_Angeles', 
            username="[email protected]");
        a = new Account(Firstname="Terry", Lastname="Testperson");
        insert a;
    }
    System.runAs(u) {
        a.PersonEmail="[email protected]";
        update a;
    }

}

Then the MIXED_DML_OPERATION errors stop happening.

Leave a Comment

Hata!: SQLSTATE[HY000] [1045] Access denied for user 'divattrend_liink'@'localhost' (using password: YES)