function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
FinnArildFinnArild 

MIXED_DML_OPERATION messing up my test

So - I'm running into one of those cases where my logic and class works fine, but the test gives me grief - I'm sure I'm not the only one experiencing that from time to time.

 

Anyway - the code and test is in here:

 

http://pastebin.com/m3ac3e655

 

This messes up my test thusly:

 

System.DmlException: Update failed. First exception on row 0 with id 005R0000000RjIfIAK; first error: MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa): User, original object: Case

 

I saw some posts mentioning this as a SFDC bug, but I found no workarounds anywhere. Can anyone help? Thanks.

Best Answer chosen by Admin (Salesforce Developers) 
werewolfwerewolf
Well, you can't insert a User and a Case (or any other normal object really) in the same operation.  You could move the post-User-creation part of your test to an @future method and then use startTest and stopTest to make the @future method execute itself and continue your test.  Or you could pull a user from the existing pool of users in the org.

All Answers

werewolfwerewolf
Well, you can't insert a User and a Case (or any other normal object really) in the same operation.  You could move the post-User-creation part of your test to an @future method and then use startTest and stopTest to make the @future method execute itself and continue your test.  Or you could pull a user from the existing pool of users in the org.
This was selected as the best answer
FinnArildFinnArild
Thanks, I ended up using an existing user.
osamanosaman

There is a work around for that.

If you want to perform two DML operations sequentially, create a seprate method for 2nd DML operation with @future token.

make sure you put System.RunAs() in the method. Your overall method should look like this

 

private static void myFunc()

{

     ///1st DML operation

 

     User usr = [Select id from User where Id = :UserInfo.getUserId()];

 

     System.RunAs(usr)

     {

        Test.startTest();

         myFunc2();

         Test.stopTest();

     }

 

 

}

 

@future

private static void myFunc2()

{

   ///2nd DML operation

}

Nani44Nani44

Hi Osaman,

 

 

Thanks for your post to the above error.