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
}
}