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
This error is so common when attempting to create user and other objects records in a single transaction in apex.
Workaround in apex class/trigger : use future method for creating user when encountered the error
Workaround in test class : don't try creating a new user data, instead use <System.runAs(new User(profileId =<required_Profile>))>
Since the test class needs to be Annotated SeeAllData=false, developer should try creating a TestUtil class to fetch the user data and call the same in the test class, code-snippet as below :
TestUtil.cls :
public static fetchRequiredProfileUser(){
return [SELECT ID, Name FROM User WHERE ProfileId ='**********'];
}
Test Class :
@isTest private void useTest(){
System.runAs(new User(TestUtil.fetchRequiredProfileUser())[0]);
}
This error is so common when attempting to create user and other objects records in a single transaction in apex.
Workaround in apex class/trigger : use future method for creating user when encountered the error
Workaround in test class : don't try creating a new user data, instead use <System.runAs(new User(profileId =<required_Profile>))>
Since the test class needs to be Annotated SeeAllData=false, developer should try creating a TestUtil class to fetch the user data and call the same in the test class, code-snippet as below :
TestUtil.cls :
public static fetchRequiredProfileUser(){
return [SELECT ID, Name FROM User WHERE ProfileId ='**********'];
}
Test Class :
@isTest private void useTest(){
System.runAs(new User(TestUtil.fetchRequiredProfileUser())[0]);
}
No comments:
Post a Comment