Error: MIXED_DML_OPERATION on setup and non-setup objects

In my test class i have the creation of a dummy custom setting and a dummy lead:

Group g1 = new Group(Name='group name', type='Queue');

            insert g1;
            QueuesObject q1 = new QueueSObject(QueueID = g1.id, SobjectType = 'Lead');

            insert q1;


    SetOwner__c mycs = SetOwner__c.getValues('standardset'); 
             if(mycs == null) {             
                 mycs = new SetOwner__c(Name= 'CustomValues');
                 mycs.OwnerId__c ='00520000000z3PrAAI';
                 mycs.RecordtypeID__c='012L00000004QsrIAE';
                 insert mycs;

    Lead lead = createNewLead(u2.id);          
                insert lead;

ERROR:

MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): SetOwner__c, original object: QueueSobject: []

I get this error because i am trying to perform DML on setup and non-setup objects in the same transaction.

Any solution for this problem?

Answer

You can resolve this in your test class by using System.runAs.

System.runAs ( new User(Id = UserInfo.getUserId()) ) {
    ...your setup-object DML...
}

If you need to do this in a non test scenario @future, Batch Apex, apex:actionFunction or something as simple as user button flow, it can be used to separate the transactions. The Salesforce documentation goes into the non test scenario a little further. This Database.com variant (equally applicable to Force.com) on the same help topic goes into the testing use case further.

Attribution
Source : Link , Question Author : Enry , Answer Author : Mark Pond

Leave a Comment