2

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?

7

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) {
    syncFutureCall(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() {
    Test.startTest();
    MyScheduledClass c = new MyScheduledClass().execute(null);
    Test.stopTest();
    // 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.

Your Answer

By clicking "Post Your Answer", you acknowledge that you have read our updated terms of service, privacy policy and cookie policy, and that your continued use of the website is subject to these policies.

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