+ Start a Discussion
gowtham murugesangowtham murugesan 

Code coverage issue for Batch apex

Hello everyone,
 
Execute method is not getting coverd in test class, Provide me the solution for this.

global class UpdateInvoiceAccount implements Schedulable,  Database.Batchable<sObject>
{
    global void execute(SchedulableContext SC) {
        Id batch =  Database.executeBatch(new UpdateInvoiceAccount(),100); 
    }
    
   global Database.QueryLocator start(Database.BatchableContext bc)
   {
      string query  =  'select id,Account__c,AccountNumber__c,LeadOn__c from Invoice__c where AccountNumber__c =\'12868\' and LeadOn__c=\'000\' and Account__r.name=\'Echuca Camera House\''; 
      return Database.getQueryLocator(query);
   }
   global void execute(Database.BatchableContext bc, List<Invoice__c> recordstoprocess)
   {
     list <Invoice__c>Invoicenew=new list<Invoice__c>();
     Map<id,Account> acMap=new Map<id,Account>();
      if(!recordstoprocess.isEmpty())
      {
          Account acts =[select id,Name from account where Name ='Raleru Ltd' and Customer_Account_and_Lead_On__c='12868   000' limit 1] ;
          for (Invoice__c inv: recordstoprocess)
          {
              Invoice__c invoice =(Invoice__c) inv;
              acMap.put(invoice.Account__c,acts);
          }
          for (Invoice__c inv: recordstoprocess)
          {
              Invoice__c invoice =(Invoice__c) inv;
              invoice.Account__c=acMap.get(invoice.Account__c).id;
              Invoicenew.add(invoice);
          }
              update Invoicenew;
      }
   }
   
   global void finish(Database.BatchableContext bc){
   }    
}

thanks.
TechingCrewMattTechingCrewMatt
Hello. There are a couple of solutions to this issue. First, you can create an InvoiceUtil class. If you move everything from the batch's execute method to the utility class, you can test the functionality by itself.

Another alternative is to excplicitly call the execute method from your tet  class as follows:
UpdateInvoiceAccount batchClass = new UpdateInvoiceAccount();
List<Invoice__c> invoices = new List<Invoice__c>([select id,Account__c,AccountNumber__c,LeadOn__c from Invoice__c where AccountNumber__c ='12868' and LeadOn__c='000' and Account__r.name='Echuca Camera House]);
Test.startTest();
batchClass.execute(null, invoices);
Test.stopTest();