[SalesForce] Unit tests executed via metadata API failing on call to system.test.startTest

I have an CI system using Jenkins and the metadata API to automatically execute all unit tests in our packaging org. Some, but not all, of the unit tests have started failing at the point where the test methods make a call to system.test.startTest(). The error is

"System.FinalException: Method only allowed during testing stack
(System Code)"

Seems pretty nonsensical since the context is most definitely a unit test class and test method. The same unit tests that fail when executed via metadata API are executing/passing without issue via dev console and standard web UI.

Thoughts anyone?

Best Answer

There is a Known Issue where if you use System.enqueueJob in code anywhere, and there are at least two test methods in the same class, it can fail with that error, a "Attempted to rollback to the wrong limit tracker" error, or an Internal Server Error (depending on the cause). A DML that fails in this class will fail with "Attempted to rollback to the wrong limit tracker" when "allOrNone" is "true", or Internal Server Error when "allOrNone" is false. The only two workarounds are to (a) not run System.enqueueJob inside a test method (guard with Test.isRunningTest()), or (b) use at most one test method per class that uses a Queueable interface class. Calling Test.startTest() or Test.stopTest() in a test method that is in an affected class will give the System.FinalException error.

Related Topic