What is Mixed DML?
Mixed DML (Data Manipulation Language) in Apex refers to a situation in which DML actions (such as insert, update, and delete) are performed on a combination of setup objects (e.g., User, Profile) and non-setup objects (e.g., custom objects, standard objects) in a single transaction. Performing DML operations on both setup and non-setup objects in the same transaction may result in runtime issues owing to Salesforce platform limitations.
When writing Apex test classes, it is critical to consider probable mixed DML scenarios, as they can lead to test failures. This often arises when the test class attempts to create or modify both setup and non-setup data within the same test function or transaction.
How to Reproduce Mixed DML in Apex Test Method
Create an Apex test class and include any setup or non-setup objects in it.
In my case, I’m inserting Account and User Role records into the Test class.
@isTest
public class MixedDMLApex {
@isTest
static void mixedDMLExample(){
//inserting Account record
Account acc = New Account();
acc.Name = 'Test Account';
acc.AccountNumber = '123456';
insert acc;
//fetch Profile record
Profile prof = [SELECT Id,Name FROM Profile WHERE Name='Standard User'];
//inserting User Role record
UserRole role = new UserRole();
role.Name = 'testRole';
insert role;
}
}
Run you Apex test class in Developer console.

When running the test class, you will receive a Mixed DML error.
Why did we receive this error in test class?
We are getting this problem because we are inserting both setup and non-setup objects in the same transaction.

Check the error below for when a test fails due to a setup or non-setup object DML operations.

Solution Approach : To tackle this issue using two Approaches, let us proceed one by one.
Approach 1 : We can break the transaction into different transactions.
We can use future method to insert User Role and break transactions.

We now have a break transaction using future method, and we are no longer receiving Mixed DML errors.
Approach 2 : In this approach, we will use the system.runas() method to create User Role records in different user contexts.
To create the User Role record in this context, we will pass any user record with the System Admin or Standard User profile using System.runAs().
See the bellow code to avoid Mixed DML error using user context.

using any of the above Approach we can avoid Mixed DML error.
Check out our Video on YouTube Channel.
One Comment
This is a really helpful blog; I’ve encountered this problem numerous times.
but now to comprehend the simple solution