+ Start a Discussion
SHAIK MOHAMMAD YASEENSHAIK MOHAMMAD YASEEN 

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';
        system.debug('Query-->'+Query);
        return database.getQueryLocator(Query);
    }
    public void execute(database.BatchableContext bc,list<sObject> scope)
    {   
        helperClass test = new helperClass();
        test.helperMethod(scope);
    }  
    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);                      
        }
        else
        { 
            System.debug('invalid batch');
            UtilityCls bu = new UtilityCls();      
            bu.sendEmailNotificationOnBatchJobFail(batchName, a.Status, a.TotalJobItems, a.NumberOfErrors,a.ExtendedStatus);
        } 
    }       
}
Raj VakatiRaj Vakati
Try this 
 
@isTest
private class AccountBatchTest {
    @testSetup 
    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() {        
        Test.startTest();
        AccountBatch  uca = new AccountBatch ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
     }
    
}