+ Start a Discussion
Ramesh KallooriRamesh Kalloori 

Batch class test class for finish method?

Hi all,

global class ContactsGeoLocationBatch implements Database.Batchable<Sobject>, Database.AllowsCallouts{

    global Database.QueryLocator start(database.batchablecontext BC){
           String Query =  'Select id, LastName,Latitude__c,Longitude__c from Contact where Primary_City__c!=null and Primary_Country__c!=null and Primary_State__c!=null and LastModifiedDate>=LAST_N_DAYS:8 order by LastmodifiedDate DESC Limit 2';     
       return Database.getQueryLocator(query);
}

global void execute(Database.BatchableContext BC, List<Contact> scope){
    for(Contact c : scope){
        if(c.id!=null)
            ContactsGeoLocationBulk.getGeoLocation(c.Id);
    }   
}  

global void finish(Database.BatchableContext BC){
//unable to get the code coverage for the below
   if(BC.getJobId()!=null)
   {
   AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,
      TotalJobItems, CreatedBy.Email
      FROM AsyncApexJob WHERE Id =
      :BC.getJobId()];*/
       if(a!=null)
       {
   // Send an email to the Apex job's submitter notifying of job completion.
   Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
   String[] toAddresses = new String[] {'XXXXXXXX@gmail.com'};//a.CreatedBy.Email
   mail.setToAddresses(toAddresses);
   mail.setSubject('Apex process has completed'+ a.Status);
   // # records were updated.
   mail.setHtmlBody('Hi,<br><br>Geocodes have been updated for all contact records modified within the last 7 days on Salesforce.com. ' + a.TotalJobItems +' records were updated.there are '+ a.NumberOfErrors + ' failures.<br><br>Thanks,<br>Ramesh.');
  Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
   }
   }
}
}

@isTest(SeeAllData = true) 
private class ContactsGeoLocationBatch_TC{
    @isTest static void testContactsGeoLocationBatch() {
      
    Test.startTest();
        Test.setMock(HttpCalloutMock.class, new ContactsMockHttpResponseGenerator_TC());          
        Database.QueryLocator QL;
        Database.BatchableContext BC;    
        List<Contact> Conlist=[Select id, LastName,Latitude__c,Longitude__c from Contact where Primary_City__c!=null 
                               and Primary_Country__c!=null and Primary_State__c!=null and LastModifiedDate>=LAST_N_DAYS:8
                               order by LastmodifiedDate DESC Limit 1];
        ContactsGeoLocationBatch c = new ContactsGeoLocationBatch();
        QL = c.start(BC);
        c.execute(BC,Conlist);
        c.finish(BC);
    Test.stopTest();
    }
}

thanks,
Ramesh
Best Answer chosen by Ramesh Kalloori
Tony TannousTony Tannous
Hi,

why you don't use the below for testing the whole batch , and it is better to remove the seeAllData and create the contact in the test Method.

isTest(SeeAllData = true)
private class ContactsGeoLocationBatch_TC
{
    @isTest static void testContactsGeoLocationBatch()
      {
         Test.startTest();
           Test.setMock(HttpCalloutMock.class, new ContactsMockHttpResponseGenerator_TC());        
           ContactsGeoLocationBatch geolocationBatch=  new ContactsGeoLocationBatch();
       geolocationBatch.Query =  'Select id, LastName,Latitude__c,Longitude__c from Contact where Primary_City__c!=null and Primary_Country__c!=null and               Primary_State__c!=null order by LastmodifiedDate DESC Limit 2';
           Database.executeBatch(geolocationBatch);
          Test.stopTest();
       }

}


And to be able to pass the Query as Parameter from the test class , you just need to remove the declation of the string Query from the start method and put it as global example: 

global class ContactsGeoLocationBatch implements Database.Batchable<Sobject>, Database.AllowsCallouts{
  global String Query='';
 global Database.QueryLocator start(database.batchablecontext BC)
{
if(Query!='')
{
  Query =  'Select id, LastName,Latitude__c,Longitude__c from Contact where Primary_City__c!=null and Primary_Country__c!=null and       Primary_State__c!=null and LastModifiedDate>=LAST_N_DAYS:8 order by LastmodifiedDate DESC Limit 2';    
}
       return Database.getQueryLocator(query);




}

Regards