35

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?

1 Answer 1

56

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.

7
  • Your most welcome! :-) Commented Jun 27, 2013 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. Commented Jun 27, 2013 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. Commented Jun 27, 2013 at 23:45
  • interestingly works for permission set test Mixed DML operation issues also, thanks! Commented Apr 8, 2014 at 17:02
  • Yeah spookly, i had just used this in some code i wrote when your upvote came through! :-) Commented Apr 9, 2014 at 2:13

You must log in to answer this question.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.