1

I'm not sure if I am completely missing something, but it seems impossible to unit test this very common scenario in Salesforce.

I need to run this test as a user with specific profiles/permissions. So I insert a new User. I also need access to some test data, eg: a couple accounts, so I try to insert those. Attempting to do this gives a Mixed DML error

  • This user type does not have permission to create accounts, so I can't stick the account creation inside of System.runAs
  • I can't use an @future because I need both the accounts and user to exist in order to complete the test logic.

I then need to use System.runAs on the created user to do some logic.

Pseudocode:

@isTest
public void myTest(){
  User testUser = insertTestUser();
  insertAccount();  // <---- Mixed DML error

  System.runAs(testUser){
    //Do some logic as test user, utilizing the account that was created
  }
}

1
  • How about if you can create the user in a @TestSetup method?
    – ManSpan
    Commented Feb 4, 2021 at 14:15

1 Answer 1

1

You create the user using System.runAs(), and then you can create the accounts as yourself (the administrator):

 User testUser = ...;
 System.runAs(new User(Id=UserInfo.getUserId()) {
   insert testUser;
 }
 Account testAccount = ...;
 insert testAccount;

Or you can do it the other way around (this is how we do it in our unit tests in production):

 User testUser = ...;
 insert testUser;
 System.runAs(new User(Id=UserInfo.getUserId()) {
   Account testAccount = ...;
   insert testAccount;
 }

And yes, this can be non-Setup objects and then Setup objects, or as done here, either way should work.

1
  • Perfect! I don't think I ever would have thought to do it like this.
    – sfdx wolf
    Commented Feb 4, 2021 at 15:13

You must log in to answer this question.

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