Testing Batch Apex

Batch Apex can be tested like any Apex code, although you are limited to a single transaction’s worth of data (one invocation of the execute method). A batch job started within a test runs synchronously, and does not count against the organization’s limit of five batch jobs.

The class in Listing 9.7 tests the Batch Apex example from Listing 9.1 and achieves 100% test coverage. The annotation IsTest(SeeAllData=true) allows the test to access the data in the organization rather than requiring it to create its own test data. Alternatively, you could modify the code to omit the annotation and insert a few Project records to serve as test data.

Listing 9.7 Batch Apex Test


@IsTest(SeeAllData=true)
public with sharing class Listing9_7 {
  public static testmethod void testBatch() {
    Test.startTest();
    Listing9_1 batch = new Listing9_1();
    ID jobId = Database.executeBatch(batch);
    Test.stopTest();
  }
}


The test method simply executes the batch with the same syntax as you have used in the Execute Anonymous view. The batch execution is bookended with the startTest and stopTest methods. This ensures that the batch job is run synchronously and is finished at the stopTest method. This enables you to make assertions (System.assert) to verify that the batch performed the correct operations on your data.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.170.174