02 Feb Adding a Test for the Batch Apex Class
In this blog, you’ll add a test class for the CleanUpRecords batch class. The test in this class invokes the batch job and verifies that it deletes all merchandise records that haven’t been purchased.
1. Click File | New | Apex Class.
2. For the class name, enter TestCleanUpBatchClass and click OK.
3. Delete the auto-generated code and add the following.
// The query used by the batch job.
'SELECT Id,CreatedDate FROM Merchandise__c '
'WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)';
// Create some test merchandise items to be deleted
// by the batch job.
Merchandise__c ml =
CleanUpRecords c =
// Verify merchandise items got deleted
Integer i = [
4. Click File | Save.
- The test class contains one test method called test. This test method starts by constructing the query string that is to be passed to the constructor of CleanUpRecords. Since a merchandise item that hasn’t been purchased is a merchandise item that doesn’t have line items associated with it, the SOQL query specifies the following:
WHERE Id NOT IN (SELECT Merchandise__c FROM Line_Item__c)
- The subquery
- gets the set of all merchandise items that are referenced in line items. Since the query uses the NOT IN operator in the WHERE clause, this means the merchandise items that aren’t referenced in line items are returned.
- The test method inserts 10 merchandise items with no associated line items to be cleaned up by the batch class method. Note that the number of records inserted is less than the batch size of 200 because test methods can execute only one batch total.
- Next, the batch class is instantiated with the query with this statement where the query variable is passed to the constructor of CleanUpRecords.
CleanUpRecords c =
- The batch class is invoked by calling Database.executeBatch and passing it the instance of the batch class:
- The call to Database.executeBatch is included within the Test.startTest and Test.stopTest block. This is necessary for the batch job to run in a test method. The job executes after the call to Test.stopTest. Any asynchronous code included within Test.startTest and Test.stopTest gets executed synchronously after Test.stopTest.
- Finally, the test verifies that all test merchandise items created in this test got deleted by checking that the count of merchandise items is zero.
- Even though the batch class finish method sends a status email message, the email isn’t sent in this case because email messages don’t get sent from test methods.
“Know more about Salesforce Consulting at Techila”