0

I'm very confused about MIXED_DML_OPERATIONerror. Following test case fails in production but passes in uat.

@IsTest
private class MyControllerTest {
    private static final String USERNAME ='[email protected]';

    @IsTest
    static void test() {
        ...
    }

    @TestSetup
    static void createMockObjects() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(
                Alias = 'tesAdmin',
                Email = '[email protected]',
                EmailEncodingKey = 'UTF-8',
                LastName = 'Test',
                LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US',
                TimeZoneSidKey='Australia/Sydney',
                ProfileId = p.Id,
                UserName = USERNAME
        );

        insert u;

        String customObjectString = '{"attributes":{"type":"Custom_Object__c"},"Name":"OBJ-01", ...}';
        Custom_Object__c customObj = (Custom_Object__c)JSON.deserialize(customObjectString, Custom_Object__c.class);
        insert customObj;
    }
}

Above test class runs perfect in UAT environment but fails in production with following error.

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

In many forums it is said that cannot perform DML Operations for setup objects and non-setup objects in the same context. If that is the case, why this runs properly in UAT?

Note: This happens only after production org is migrated to a different server.

1 Answer 1

0

I'm not sure why this runs properly in UAT. But you can fix it by using System.runAs()

@TestSetup
    static void createMockObjects() {
        Profile p = [SELECT Id FROM Profile WHERE Name='System Administrator'];
        User u = new User(
                Alias = 'tesAdmin',
                Email = '[email protected]',
                EmailEncodingKey = 'UTF-8',
                LastName = 'Test',
                LanguageLocaleKey = 'en_US',
                LocaleSidKey = 'en_US',
                TimeZoneSidKey='Australia/Sydney',
                ProfileId = p.Id,
                UserName = USERNAME
        );

        system.runAs(u){
            String customObjectString = '{"attributes":{"type":"Custom_Object__c"},"Name":"OBJ-01", ...}';
            Custom_Object__c customObj = (Custom_Object__c)JSON.deserialize(customObjectString, Custom_Object__c.class);
            insert customObj;
        }
        
    }
1
  • I know, this way I can fix this. I'll update the question with another example. Thank you for your answer anyway! Commented Sep 13, 2020 at 4:38

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .