I have a test that for it's data setup I need to fire multiple asynchronous processes. I have a suspicion, that they do not finish sequentially one after another.

I think Test.startTest()/Test.stopTest() methods can only wait for one process to complete. What are workarounds for data setup without writing a separate class for each method or relying on @testSetup too much?


Test.startTest does not wait for any asynchronous code to run. Test.stopTest can test multiple asynchronous code calls within reason (e.g. a scheduled class that calls a batch class), but there are particular limits (e.g. a batch class cannot call another batch class).

You will necessarily need to test each of your processes in separate tests in order to make sure your coverage is adequate. This means you may need to rig your asynchronous code in a way that runs synchronously for most tests, such as calling future methods by proxy:

@testVisible static void syncFutureCall(Id[] params) {
    // Do stuff here
@future public static void futureCall(Id[] params) {

In your test methods, use the syncFutureCall method for data setup, and use futureCall when you're actually trying to unit test the future call. You can use similar designs for schedulable and batchable classes. In fact, I usually prefer to call batchable or schedulable code directly, for coverage purposes:

@isTest static void testScheduledClass() {
    MyScheduledClass c = new MyScheduledClass().execute(null);
    // Observe changes to c or the database to make sure it ran as expected.

In my opinion, the "feature" they built in to Test.stopTest isn't robust enough. There should be an explicit Test.executeAsync function, which would let us clear out future calls and so on.

  • FYI: For platform Events there is a method to force execution:"Test.getEventBus().deliver();" That way you can execute and assert multiple updates (that trigger platform events) in a single test method. – Schnaps Jul 26 at 8:25

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.