Tag Archives: Limits

Testing Batch Apex

21 Aug

I recently had to publish a batch Apex class to our production org and had a tough time doing it thanks to issues with the associated test.

If you read the official documentation, it’s a little vague about the limitations involved in testing batch code and if you get things wrong, your test will probably run but show very low coverage (specifically just the start method showing coverage).

Digging through the discussion boards lead me to this post which outlines the solution.

Basically you’re only allowed to run one batch of 200 records for your test. That means you have to be able to add LIMIT 200 to your SOQL query in your test class and you can only have one call to Database.executeBatch() within your test class. You also need to wrap that call within Test.startTest() and Test.stopTest(). The start test signals the system to collect all async code and then it’s executed after the stop test.

You could just make your SOQL query a public string and default it to your “live” query then your test code would look something like:

Test.startTest();
MyBatchClass mb = new MyBatchClass();
 mb.theQuery = mb.theQuery + ' limit 200';
 String Id = Database.executeBatch( mb, 200);
Test.stopTest();

Providing  direct access to the query like that though isn’t really ideal coding.  It would be better to add a public method say runAsTest() to your batch which you could call from your test class and have that do the addition of the limit text, therefore protecting your carefully crafted query from the clutches of anything that might mess with it.