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
Samuel WolfeSamuel Wolfe 

How to insert both a user and an account before Test.startTest() (mixed DML)

So I am confused. I need to be able to insert a new User with a specific profile/permission sets and a new account before starting my Test.startTest block.

If I create the User first, then creating the account causes
MIXED_DML_OPERATION, DML operation on setup object is not permitted after you have updated a non-setup object (or vice versa)
The documentation recommends using @future methods, but this won't work because I need the guarantee that both the account and user exist before running my test.

How do you accomplish this?
 
Best Answer chosen by Samuel Wolfe
Samuel WolfeSamuel Wolfe
Ok I figured it out. You need to create 2 users. One as a system administrator and one as a user with the profile you want to test.

Then you use System.runAs(Admin) to create the account, and System.runAs(userToTest) to actually perform the test.
 
//Create 2 users, one as a System Admin who can create account
//And one as the user with the profile I want to test

User administrator = createUser('System Administrator');
User userToTest = createUser('Test Profile');

//Create the test account with the system administrator I just created
system.runAs(sysAdmin){
    createAccount();
}

//Now I can run the test as the other user, with the account already created
system.runAs(userToTest){
    <Code To Test Here>
}