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
StarhunterStarhunter 

Mixed DML operation error in test class

I have a few queries related to test class in general and mixed DML error in specific.
1. What does running a test class in system mode mean?
Does it mean running the test class in the context of the current user and is that same as saying :
System.runAs(new User((Id=UserInfo.getUserId()) )){ //test code}.
2. Following is the code snippet of the test class I have written:
static testmethod void method1()
{
    User u1 = DataFactory.createUser('testUser','test@user.com','permissionSetAPIname');  

    system.runAs(new User(Id=UserInfo.getUserId()))
    {
    Obj1 rec1 = DataFactory.createrec1('Record1');
    insert rec1;

    Obj2 rec2 = DataFactory.createrec2('Rec2',rec1,system.today()-10, system.today()+10 );
    insert rec2; 

    Obj3 rec3 = DataFactory.createrec3(rec2,'Tester',u1,'US');
    insert Role;

    test.starttest();   

    //testing code

    test.stoptest();
    }

}

On removing the System.runAs(), the test class fails giving the mixed DML error. 

3.  The following code works without any error:
static testmethod void method1()
{
    User u1 = new User(Alias = 'testRole',
                  Email             = 'role@test.com',
                  EmailEncodingKey  = 'UTF-8',
                  LastName          = 'user',
                  FirstName         = 'test',
                  LanguageLocaleKey = 'en_US',
                  LocaleSidKey      = 'en_US',
                  ProfileId         = [select Id from Profile where Name = 'Basic User' limit 1].Id,
                  TimeZoneSidKey    = 'America/Chicago',
                  Username          = 'stakeholder@test' + Math.round(Math.random() * 10000) + '.com',
                  UserRoleId        = null,
                  Country           = 'Great Britain');
    insert u1;    

    
    Obj1 rec1 = new Obj1(name='Record1');
    insert rec1;

    Obj2 rec2 = new Obj2(name='Rec2',field2__c=rec1.id,start_date__c=system.today()-10, end_date__c=system.today()+10 );
    insert rec2; 

    Obj3 rec3 = new Obj3(field3__c=rec2.id,field22__c='Tester',user__c=u1.id,field222__c='US');
    insert rec3;

    test.starttest();   

    //testing code

    test.stoptest();
    

}

I mean if I consider that Mixed DML error occurs because salesforce prevents updating setup object(user in this case) and non set up object in the same transaction., how is the insert operations in the above case part of different transactions.
I am new to salesforce. Please explain in simpler terms.