0

we've a factory class method to create sObject:

Class: DataFactory: 

    public static SObject createSObject(SObject sObj, String defaultClassName, Boolean doInsert) {
        SObject retObject = createSObject(sObj, defaultClassName);
        if (doInsert) {
            insert retObject;
        }
        return retObject;
    }

Helperclass:

  @TestSetup
    static void dataSetup(){
       
        Id rtVBAccount = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Vendor_Builder').getRecordTypeId();
        
        Profile rewProfile = [SELECT id,Name,UserType FROM Profile WHERE UserType='PowerCustomerSuccess' LIMIT 1];
        
        Account vb = (Account) DataFactory.createSObject(
            new Account(Name='VB1',RecordTypeId=rtVBAccount), 'rew_DataFactory.VendorBuilderAccountDefaults', true);
        
        
        Contact rewCon = (Contact) DataFactory.createSObject(
            new Contact(AccountId=vb.Id),'rew_DataFactory.ContactDefaults', true); 
        
        
        User rewUsr = (User) DataFactory.createSObject(
                new User(ContactId=rewCon.Id,ProfileId=rewProfile.Id,UserRoleId=rewUsrRole.Id),'rew_DataFactory.UserDefaults', true); 
        
    }

I am trying to insert setup (Profile and Role)and Non setup objects(Contact) in Helper Class. When I am trying to run the test class below is the 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: Account: []'

Can some one help me how to pass System.runAs(){} in the below code to resolve this Mixed DML exception?

1 Answer 1

0

Instead of "passing in" a runAs, which would burn a lot of unnecessary DML statements, just wrap the setup parts in a runAs:

 @TestSetup
    static void dataSetup(){
        Id rtVBAccount = Schema.SObjectType.Account.getRecordTypeInfosByDeveloperName().get('Vendor_Builder').getRecordTypeId();
        
        Profile rewProfile = [SELECT id,Name,UserType FROM Profile WHERE UserType='PowerCustomerSuccess' LIMIT 1];
        
        Account vb = (Account) DataFactory.createSObject(
            new Account(Name='VB1',RecordTypeId=rtVBAccount), 'rew_DataFactory.VendorBuilderAccountDefaults', true);
        
        
        Contact rewCon = (Contact) DataFactory.createSObject(
            new Contact(AccountId=vb.Id),'rew_DataFactory.ContactDefaults', true); 
    User rewUsr;
    System.runAs(new User(...)) {
        rewUsr = (User) DataFactory.createSObject(
                new User(ContactId=rewCon.Id,ProfileId=rewProfile.Id,UserRoleId=rewUsrRole.Id),'rew_DataFactory.UserDefaults', true); 
        }
    }
0

You must log in to answer this question.

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