+ Start a Discussion

test class for batch class, need to cover else part if batch has failed in finish method

Hi All,

I am having code below. for a batch, when ever my batch fails i will send an email to admin with the current batch status, can you please help me how to cover the else part in the finish method. 

public class AccountBatch implements Database.Batchable<sObject>
    public database.QueryLocator start(Database.BatchableContext bc)
        string Query='select id, Name From Account';
        return database.getQueryLocator(Query);
    public void execute(database.BatchableContext bc,list<sObject> scope)
        helperClass test = new helperClass();
    public void finish(Database.BatchableContext bc)
        AsyncApexJob a = [Select Id, Status, NumberofErrors, JobItemsProcessed, TotalJobItems, CreatedBy.Email, ExtendedStatus
                          from AsyncApexJob
                          Where Id =:bc.getJobId()];
        String batchName = 'AccountBatch';                
        If(a.Status=='Completed' && a.NumberofErrors==0)
            Database.executeBatch(new nextBatch(),50);                      
            System.debug('invalid batch');
            UtilityCls bu = new UtilityCls();      
            bu.sendEmailNotificationOnBatchJobFail(batchName, a.Status, a.TotalJobItems, a.NumberOfErrors,a.ExtendedStatus);
Raj VakatiRaj Vakati
Try this 
private class AccountBatchTest {
    static void setup() {
        List<Account> accounts = new List<Account>();
        List<Contact> contacts = new List<Contact>();
        // insert 10 accounts
        for (Integer i=0;i<10;i++) {
            accounts.add(new Account(name='Account '+i, 
                billingcity='New York', billingcountry='USA'));
        insert accounts;
        // find the account just inserted. add contact for each
        for (Account account : [select id from account]) {
            contacts.add(new Contact(firstname='first', 
                lastname='last', accountId=account.id));
        insert contacts;
    static testmethod void test() {        
        AccountBatch  uca = new AccountBatch ();
        Id batchId = Database.executeBatch(uca);