I need to write a test that verify that a function call is run synchronously.

As I have found no elegant way to find that out I now let my function run into a Limit which is an indirect proof that the code did NOT run asynchronously.

private static void canBeForcedToRunSynchronously() {
    // Setup
    Map<Id, Opportunity> opps = insertOppsToManipulate(TO_RUN_SYNCH_DONT_EXCEED + TOO_MUCH);
    SmartBatch batch = new SetOppAmountToValue(opps.values(), 666);

    // Execute
    Test.startTest(); // Not needed to let batch run synchronously but to resetLimits

    // Verify
    Boolean thisLineWillNotbeReached = false;

1 Answer 1


You don't need anything to prove that a method call is run synchronously since Apex is effectively a single threaded language. Sure, @Future calls and batch Apex execute asynchronously when you're not running unit tests, but when you call Test.stopTest from within a test method it forces everything to execute in a synchronous fashion.

The only way this would become an issue is if you launched an @Future method from batch Apex or visa-versa, but you can't do that without hacking things (using the finish method of batch Apex to launch another async process) and definitely can't do it from within a test method.

So you're already running things synchronously in a unit test.

  • Might be true but not at all an answer to my question whether you can verify in a unit test that a method runs into a limit. May 28, 2013 at 19:59
  • 1
    Limits are uncatchable errors so running into them directly is one way to do this. Another is to use Limits calls to proactively determine if you're going to hit limits or not. This is the best approach. Also, the description of your question seems to imply that running into limits is just providing indirect proof that you are not running asynchronously.
    – Adam
    May 28, 2013 at 23:51

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .