[SalesForce] How to Get Mixed DML in a Unit Test

I'm trying to demonstrate the usage of System.runAs() to avoid mixed dml errors in unit tests. I know I've had to do some trickery when working with setup objects and then running tests. It is also documented. For example, I thought this test class would throw the error, but it isn't. Did something change in how tests run?

@isTest
private class RunAsTest {

    @isTest static void mixedDml() {
        Profile p = [select id from profile where name='Standard User'];
        UserRole r = [Select id from userrole where name='COO'];
        User u = new User(alias = 'standt', email='standarduser@testorg.com', 
                emailencodingkey='UTF-8', lastname='Testing', 
                languagelocalekey='en_US', 
                localesidkey='en_US', profileid = p.Id, userroleid = r.Id,
                timezonesidkey='America/Los_Angeles', 
                username='standarduser3234234@testorg.com');
        insert u;
        Account a = (Account) TestFactory.createSObject(new Account());
        insert a;

        //System.runAs(u) {
            a.Name = 'New Name';
            update a;
        //}
    }
}

Best Answer

I got a mixed dml exception with the following code.

@isTest
public class testTester {
    public static testmethod void testMixedDml() {

        Profile p = [select id from profile where name='Standard User'];

        User u = new User(alias = 'standt', email='standarduser@testorg.com', 
                emailencodingkey='UTF-8', lastname='Testing', 
                languagelocalekey='en_US', 
                localesidkey='en_US', profileid = p.Id,
                timezonesidkey='America/Los_Angeles', 
                username='standarduser3234234@testorg.com');
        insert u;


        Group g = new Group();
        g.Name = 'Test Group';
        g.DeveloperName = 'TestGroup';
        insert g;

        GroupMember gm = new GroupMember();
        gm.GroupId = g.Id;
        gm.UserOrGroupId = u.Id;
        insert gm;


        Account a = new Account();
        a.Name = 'Test Account';
        insert a;
    }
}