28

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?

42

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.

  • Your most welcome! :-) – Andrew Fawcett Jun 27 '13 at 13:17
  • 1
    Hey @ca_peterson, thanks for the tweak nice optimisation! Not sure where I first heard about it tbh, though I did actually find this pattern well covered in several blogs forums and sf docs as I was checking my understanding of it. – Andrew Fawcett Jun 27 '13 at 23:42
  • 1
    Hope you don't mind, I edited your answer to create the User sobject in memory instead of from the database - helps avoid an extra query. – ca_peterson Jun 27 '13 at 23:45
  • interestingly works for permission set test Mixed DML operation issues also, thanks! – realnumber Apr 8 '14 at 17:02
  • Yeah spookly, i had just used this in some code i wrote when your upvote came through! :-) – Andrew Fawcett Apr 9 '14 at 2:13

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.