1

Imagine the following scenario:

Trigger myTrigger on User calls a future method which flags Account records. Then a Batch Job must run to process the records.

While testing, I am first inserting User records and then calling the Batch job. I am expecting BOTH to run since they are called before the Test.Stop() as mentioned in the documentation.

Is there any guarantee than my future method will ALWAYS run before the Batch job. Although my tests have proven so, till now, I assume it may happen that the order is not preserved.

2

You have run into a problem I've had as well.

Short answer: There is no guarantee in the documentation because it is entirely possible that the future method will run two minutes later, given platform resources, but the batch job would be invoked immediately... and then you have the batch job (in my case) selecting zero records because none have been updated by the future to have the right field value criteria for the batch.

I ended up writing synchronous code in parallel with the asynchronous (future) code, doing code reuse by returning a list of records in the method so that I can call that method in my before update trigger section, or call it and then perform DML on the returned list in my future after update trigger section.

Then for testing the batch, you set a static boolean (I call it forceSynchronous) to true, and the trigger has the logic to run synchronous code and then do the batch. For testing the future code, you leave the boolean as false and just do your asserts on what you would expect the future code to output. You don't ever end up doing end-to-end future + batch, but with enough asserts, you don't need to.

  • I hit this exact same issues yesterday... seems like it's not a particularly rare occurance thanks to the mixed DML restrictions. – Matt Lacey May 22 '14 at 23:41
  • Thanx ! I was also considering setting the static variables to control the trigger, but I ended up with a simpler approach. I test the batch separately and I set explicitly the flag so I don't have a dependency with the future job. In normal operation (not tests) the batch will run 2/hour so its not a big problem if I miss a run – ManSpan May 23 '14 at 8:33

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.