+ Start a Discussion
Prabhat AroraPrabhat Arora 

Test Class for Apex batch job, not covering the execute method in batch: Coverage Missing!!

Hi All, I had created a batch job, for which i am writing a test class, batch class is working fine but i am missing something in Test Class, below is the code snippet of both of my classes, my Test class is not covering the execute method of the  batch job, resulting in just 37% of code coverage. It would be a great help  if somebody can help me in figuring out the issue.
***********My Batch Class***********
global class CreateMissingentitlementWithSA  implements Database.Batchable<sObject> {
   List<String> Reclist = new List<String>{'Renewal - Booked', 'Renewal'};   
   List<String> StgVal = new List<String>{'Closed Won'};
   public String  Query='Select id, OpportunityId,Opportunity.stageName, Name from OpportunityLineItem where OpportunityId Not In (Select Opportunity__c From Entitlement__c)';   
 global database.querylocator start(Database.BatchableContext BC)
  return Database.getQueryLocator(Query);
 global void execute(Database.BatchableContext BC, List<sObject> scope) {
    list<OpportunityLineItem> Opp=new list<OpportunityLineItem>();
    set<Id> Opptyids=new set<Id>();
    set<Id> OpsId=new set<Id>();
    list<opportunitylineItem> listOLIs = new list<opportunitylineItem>();
     for(sObject s : scope){
         OpportunityLineItem op = (OpportunityLineItem)s;
        listOLIs = [SELECT OpportunityId, id,Product2id,Number_of_SAT_Hours__c,Number_of_Units__c ,PricebookEntryId FROM OpportunityLineItem where OpportunityId not in (select opportunity__c from entitlement__c) and Product2.family = 'Product Bundle' and Product2.Web_Site_Id__c!='' and id in :Opptyids];

        if(listOLIs!=null && listOLIs.size()>0)
            ConvertedOLIWorkflows objConvertedOLIWorkflows = new ConvertedOLIWorkflows (listOLIs );
            objConvertedOLIWorkflows.createEntitlementAfterOLI(listOLIs );
        system.debug('Check If Entitlements Addedd Successfully');
         list<Service_Access__c> SAlist =  new list<Service_Access__c>();   
         SAlist= [Select id, Sold_Opportunity__c from Service_Access__c where Sold_Opportunity__c In:OpsId];       
         Map<Id, Id> SAOptyMap = new Map<Id, Id>();
         If (SAlist!=null)
          for (Service_Access__c SA:SAlist) 
          SAOptyMap.Put(SA.Sold_Opportunity__c, SA.Id);
          list<Entitlement__c> EntLst = new list<Entitlement__c>();
          EntLst= [Select id, Opportunity__c, Service_Access__c from Entitlement__c where Opportunity__c In:OpsId];
          for(Entitlement__c Ent:EntLst ){
          Ent.Service_Access__c= SAOptyMap.get(Ent.Opportunity__c);
          Update EntLst;
    global void finish(Database.BatchableContext BC){
   AsyncApexJob a = [Select Id, Status, NumberOfErrors, JobItemsProcessed,
                      TotalJobItems, ExtendedStatus,CreatedBy.Email
                 from AsyncApexJob where Id =:BC.getJobId()];
     //Send an email to the Apex job's submitter notifying of job completion.
       Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
       String[] toAddresses = new String[] {a.CreatedBy.Email};
       mail.setSubject('Add missing entitlements batch job ' + a.Status );
             ('The batch Apex job processed ' + a.TotalJobItems +
           ' batches with '+ a.NumberOfErrors + ' failures due to'+ a.ExtendedStatus  );
          Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
*******my Test Class for the above batch***
private class CreateMissingentitlementWithSATestClass{

    static testMethod void myTest() {
          Id rtid = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal').getRecordTypeId();

          Id rtid1 = Schema.SObjectType.Opportunity.getRecordTypeInfosByName().get('Renewal - Booked').getRecordTypeId();
          Product2 p = new product2(name='Test Product', Family = 'Product Bundle', Discount_No_Approval__c=10, Discount_FL_Approval__c=25, Discount_GL_Approval__c =50, Discount_Finance_Approval__c =75, Web_Site_Id__c = 'test');
          insert p;
          Bundled_Components__c bundComp = new Bundled_Components__c(CurrencyIsoCode='USD', Parent_Product__c=p.id);
          insert bundComp;
          insert new PricebookEntry(unitprice = 100.0, product2id = p.id, pricebook2id = Test.getStandardPricebookId(),isActive=true);
          Pricebook2 pb = new pricebook2(name='test pricebook');
          insert pb;
          PricebookEntry pbe = new PricebookEntry(pricebook2id=pb.id, product2id=p.id, unitprice=100.0, isActive=true);
          insert pbe;  
          account acc = new account(Type = 'LE', Membership_Type__c = 'Standard', AnnualRevenue = 100, Name = 'SaurabhTest', NumberOfEmployees = 2, Region__c = 'NA');
          insert acc;                             
          Contact c = new Contact(AccountID =acc.Id, FirstName='FirstName', LastName='Testing Contact',Title='Naveen', Email='test14@gmail1421.com', Mailing_Address_1__c='Delhi');
          insert c;

                         opportunity oppNew = new opportunity();
                         oppNew.Gartner_Opportunity_ID__c = 'o12345'; 
                         oppNew.Amount = 0 ;
                         oppNew.Pricebook2Id = pb.id ;
                         oppNew.GTS__c = true;
                         //oppnew.TerritoryId = TerritoryId;
                         //oppnew.ownerId = OwnerId;
                         oppNew.Main_Contact__c = c.id ;
                         oppNew.accountId = acc.id;
                         oppNew.stageName = 'Prospecting';
                         oppNew.CloseDate = Date.today();
                         oppNew.Name = 'GTS Opportunity';
                         insert oppNew;
          OpportunityLineItem oli = new OpportunityLineItem(Allow_Delete__c=true, Manual_Pricing__c=true,opportunityid=oppNew.id,UnitPrice=100, quantity=1,
          insert oli;
     CreateMissingentitlementWithSA ent = new CreateMissingentitlementWithSA();
     Id batchId = Database.executeBatch(ent); 

Best Answer chosen by Prabhat Arora
Naval Sharma4Naval Sharma4
Looks like there are no records are returned by the start method. Can you not put a debug statement in the start and check if your query is returning a row?

If start is returning a batch ( which is rows returned by the query locator) then only it will go in the execute method.


All Answers

Naval Sharma4Naval Sharma4
Looks like there are no records are returned by the start method. Can you not put a debug statement in the start and check if your query is returning a row?

If start is returning a batch ( which is rows returned by the query locator) then only it will go in the execute method.

This was selected as the best answer
Prabhat AroraPrabhat Arora
Thanks Naval!! I was missing on this silly point, while manual testing in my sandbox, i was left with no records retuning for query!!
Prabhat AroraPrabhat Arora
Hi, i am Stucking on one more issue: for the above batch i am executing like:
Id batchJobId = Database.executeBatch(new CreateMissingentitlementWithSA(), 1);

though i am passing  the size for 1 record only, my batch is executing for all records, i am  not sure what i am missing on?