1

I have a batch job which sends an email notification in case of any failures and the logic is working fine. However I am not able to write code coverage for the email part and it is due to I am unable to produce any errors. Just wondering how would test scenarios like this.

AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems FROM AsyncApexJob WHERE Id =      :BC.getJobId()];

            If(job.NumberOfErrors>0){
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                String[] toAddresses = new String[] {'test@test.com'};
                mail.setToAddresses(toAddresses);
                mail.setSubject('Batch Failure');
                mail.setPlainTextBody('The batch Apex job processed ' + job.TotalJobItems +' batches with '+ job.NumberOfErrors + ' failures.');
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
            }

Is there anyway I can have code coverage by forcing errors. One solution I thought is, Check Test.isRunningTest() and throw an exception in the execute method but not sure that is right thing. Would appreciate any input.

1

This is how you can do:

Create a separate method in batch class:-

     public void sendEmail(String body)
     {
                Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
                String[] toAddresses = new String[] {'test@test.com'};
                mail.setToAddresses(toAddresses);
                mail.setSubject('Batch Failure');
                mail.setPlainTextBody(body);
                Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
     }

In test class call this method in separate as:

public static testmethod void testTheEmail()
{
      batchInstance.sendEmail(' Batch failed with.... bla bla ');
}

Main batch class would look like:

        AsyncApexJob job = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems FROM AsyncApexJob WHERE Id =      :BC.getJobId()];

        If(job.NumberOfErrors>0)
        {
            sendEmail('The batch Apex job processed ' + job.TotalJobItems +' batches with '+ job.NumberOfErrors + ' failures.');
        }
0

I've not seen the rest of your code, but all you need to do is populate your test data with something you know that will cause an exception or error to occur that your handler will pick up. You want to know that it's picking up the kind of error you expect it to and be able to assert that it was successful in doing that. The response to your actual email method as you know will be mocked.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.