[SalesForce] Mixed DML operation error on User Trigger breaking test classes

I have a user trigger that upserts both setup objects and custom settings records for provisioning purposes, and have everything in @future methods to avoid mixed DML operation errors. All of our test classes are breaking however, as almost all of them insert users. Does anyone have a workaround for this, besides doing something like adding System.runAs to all other test classes?

Best Answer

Gonna go on a hunch here.

I learned the hard way that Mixed object DML is a powerful, but quirky tool. One of the things I learned is that it acts like the list is split into lists by adjacent type. In other words, if your List contains elements of User, Account and Opportunity (U, A and O respectively) like this:

UAAAUUOOOUAUO

That list will be "broken" into 8 sub lists by the DML call like this:

U
AAA
UU
OOO
U
A
U
O

This can quickly hit the "max chunks" limit.

Thankfully, a quick list.sort(); call will result in a mix-dml list like this UUUUUAAAAOOOO, which is broken into only 3 "chunks".

Try sorting your list before insert/update/etc. See if that Helps?