1

I know that you can test batchable Apex code by calling the Database.executeBatch() function. For example:

Database.executeBatch( batchable_instance );

However, I have inconsistent results with any test assertions that I make. Also, the Salesforce documentation says that "you can test only one execution of the execute method." How can I avoid executing the execute method multiple times?

1 Answer 1

1

Database.executeBatch() is an asynchronous call, so you can't be sure when it will execute. To avoid the problem with assertions, surround your code with the Test.startTest() and Test.stopTest() functions. For example:

Test.startTest();
Database.executeBatch( batchable_instance );
Test.stopTest();

The Test.stopStatus() call will force the code to execute if it already hasn’t. Then you should be able to make your assertions.

To avoid executing the execute method multiple times, you can use Test.isRunningTest() to add a limit to your query. For example:

(Test.isRunningTest() ? ' limit 5' : '');

3
  • Do you see in the debug logs that when wrapped as shown above, execute() gets called more than once? (regardless of using Limit)
    – cropredy
    Aug 8, 2015 at 0:48
  • @crop1645 I've only seen that when you set a non-standard batch size, like Database.executeBatch(batchable_instance, 1). In this a limit of 5 should be fine from my experience. Aug 8, 2015 at 4:09
  • @ca_peterson - hmm, learned something new. I had always thought that execute() in test context was called only once and designed tests accordingly
    – cropredy
    Aug 8, 2015 at 14:58

You must log in to answer this question.

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