Search

Tuesday 4 October 2011

This Is The Strangest Thing Ive Seen In Salesforce

So do we all agree that there's no problem if you want to insert a record on 1 object and after that has inserted correctly, no problem, you
immediately want to insert another record on a different object.

Wrong! You must be joking right. I do this all the time. Well there are certain times when this is not possible
I was making a unit test in a Sandbox and I was populating a custom setting with data. Then immediately after I was trying to insert
an Account record. Now I'd setup my test data I then performed my unit tests and ran the unit test in Eclipse. The unit test passed. Perfect.
Then later that day I was running All Tests in the same sandbox and to my surprise my new unit test failed. I knew there hadn't been any changes to code, meta data, data, or anything
on my sandbox. So after some investigation I came across this article

http://stackoverflow.com/questions/2387475/how-to-avoid-mixed-dml-operation-error-in-salesforce-tests-that-create-users

I also looked at
http://www.salesforce.com/us/developer/docs/apexcode/Content/apex_dml_non_mix_sobjects.htm

From this information I wrapped System.runas around the insert statement that created the custom setting record to run this code as System Administrator, as shown below. The result was the unit test passed in both Eclipse and in the browser when I logged into Salesforce.

    Profile systProfileID = [Select id From Profile where Name Like 'System Administrator' LIMIT 1];
    list<User> us1 = [Select id From User where ProfileID=: systProfileID.id and IsActive=true limit 1];
   
    if (us1.size() > 0){
        System.runAs(us1[0]){
            //insert custom setting record
        }
    }

    //now you can safely insert any standard object record


This certainly qualifies as 1 of the most strangest bugs I've come across in Salesforce. Be aware!

No comments:

Post a Comment

Note: only a member of this blog may post a comment.