Testing Batch Apex
We have now seen in this chapter the different use cases and ways of invoking Batch Apex jobs. The final thing we need to do is be able to test our batch code appropriately to ensure that the code runs as expected. This is a critical step as Batch Apex processes run across a large volume of data and can therefore have repercussions if incorrect updates or changes are made. For example, if a batch job is used to recreate the sharing settings for an organization and makes the incorrect adjustments, this can have severe consequences and potential legal implications around data sharing.
Batch Apex is like other forms of asynchronous Apex where we test it using the Test.startTest()
and Test.stopTest()
methods to trigger the asynchronous operation to fire; for example:
Test.startTest(); Database.executeBatch(new ExampleBatch()); Test.stopTest(); //Verify behaviour of batch class was as expected
While this is simple to implement and follows the same pattern as...