+ Start a Discussion
Gaurav AgnihotriGaurav Agnihotri 

Only 39% code coverage for a batch insert class

Gurus, 
I am trying to insert data into Product2 and PriceBookEntry from a staging Object Product_Stage__c

The class is as follows:
global class batchPInsert  implements Database.Batchable<sObject>,Database.Stateful
{
  global integer SizeP = 0;
    global Database.QueryLocator start(Database.BatchableContext BCPI)
    {
        string operation;
        operation='Insert';
        String query = 'SELECT CCO_Standard_Cost__c,IsActive__c,Dealer_Price__c,Description__c,Discount_Code__c,IP_Classification__c,Item__c,Name,Product_Type__c,Salesforce_Id__c FROM Product_Stage__c';
        query=query +' WHERE Operation_Type__c = \'' + String.escapeSingleQuotes(operation) + '\'';
        return Database.getQueryLocator(query);
    }
   
    global void execute(Database.BatchableContext BCPI, List<Product_Stage__c> scope)
    {
        List<Product2> lstP = new List <Product2>();
        List<PriceBookEntry>lstPBE=new List <PriceBookEntry>();
        Id StandardPriceBookID=[SELECT Id FROM Pricebook2 WHERE Name = 'Standard Price Book'].Id;
        for(Product_Stage__c PStg : scope)
         {
           Product2 P = new Product2();
           PriceBookEntry PBE=new PriceBookEntry();
           P.CCO_Standard_Cost__c=PStg.CCO_Standard_Cost__c;
           P.Dealer_Price__c=PStg.Dealer_Price__c;
           P.Description__c=PStg.Description__c;
           P.Discount_Code__c=PStg.Discount_Code__c;
           P.IP_Classification__c=PStg.IP_Classification__c;
           P.Item__c=PStg.Item__c;  
           P.Name=PStg.Item__c;
           P.Product_Type__c=PStg.Product_Type__c;
			P.IsActive=PStg.IsActive__c;
           lstP.add(P);
           insert(lstP);
           PBE.Pricebook2Id=StandardPriceBookID;
           PBE.Product2Id=P.Id;
           PBE.UnitPrice=P.Dealer_Price__c; 
           PBE.IsActive=True;
           lstP.clear();
           lstPBE.add(PBE);
         }
        SizeP+=scope.size(); 
        insert(lstPBE);
        delete(scope);
    }   
    global void finish(Database.BatchableContext BCPI)
    {
        String email;
        //email='gagnihotri@pelco.com';
        AsyncApexJob a = [SELECT Id, Status, NumberOfErrors, JobItemsProcessed,TotalJobItems, CreatedBy.Email FROM AsyncApexJob WHERE Id =:BCPI.getJobId()];
        //SizeP= [SELECT Count() from Product_Stage__c WHERE Operation_Type__c = 'Insert'];
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
		mail.setToAddresses(new String[] {'gagnihotri@pelco.com','nhombal@pelco.com','dfisher@schneider-electric.com','ron.adolph@schneider-electric.com'});
		mail.setReplyTo('gagnihotri@pelco.com');
		mail.setSenderDisplayName('Batch Processing');
		mail.setSubject('Batch Process Completed for insert on Products');
		if (a.Status == 'Completed')
		mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches of batch size '+ SizeP+ ' with '+a.NumberOfErrors + ' failures.');		
        //if (a.Status == 'Failed')
        //mail.setPlainTextBody('The batch Apex job processed ' + a.TotalJobItems +' batches of batch size '+ SizeP+ ' with '+a.NumberOfErrors + ' failures. Failure Message: '+a.ExtendedStatus);	
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}

The Test class:
@istest
private class TestBatchPInsert {
	static testMethod void batchPMethod1(){
        Id SPBId=test.getStandardPricebookId();
        Product2 P=new Product2();
        P.CCO_Standard_Cost__c=109071.45;
        P.Dealer_Price__c=441373.0;
        P.Description__c='CM9770-992X128 High Density System';
        P.Discount_Code__c='D';
        P.IP_Classification__c='Analog';
        P.IsActive=true;
        P.Item__c='CM9770-992X128';
        P.Name='CM9770-992X128';
        P.Product_Type__c='Matrix';
        insert P;
        PriceBookEntry PBE=New PriceBookEntry();
        PBE.Pricebook2Id=SPBId;
        PBE.Product2Id=P.Id;
        PBE.UnitPrice=100;
        //PBE.Name='CM9770-992X128';
        //PBE.ProductCode='AU';
        Insert PBE;
      	Product_Stage__c PStg= new Product_Stage__c();
        PStg.CCO_Standard_Cost__c=109071.45;
        PStg.Dealer_Price__c=441373.0;
        PStg.Description__c='CM9770-992X128 High Density System';
        PStg.Discount_Code__c='D';
        PStg.IP_Classification__c='Analog';
        PStg.IsActive__c=true;
        PStg.Item__c='CM9770-992X128';
        PStg.Name='CM9770-992X128';
        PStg.Product_Type__c='Matrix';
        PStg.Salesforce_Id__c=P.Id;
        insert PStg;
        
        system.debug('Product Stage Id='+PStg.Id);
        //Test Start
      	Test.StartTest();
		batchPInsert  pr4= new batchPInsert ();
		database.executeBatch(pr4);
        //pr4.execute(null, new list<Product_Stage__c> {PStg});
        //pr4.execute(null, new list<Product_Stage__c> {PStg});
		Test.StopTest(); 
        //Test Stop
    }
}

The complete execute function  has zero code coverage.
Error Code Coverage in RED

Any suggestions?
Gaurav
Best Answer chosen by Gaurav Agnihotri
ClintLeeClintLee
Hi Gaurav,

The query in your batch class has WHERE Operation_Type__c = 'Insert'.  

It doesn't look like you added an Operation Type when you created the record in your test class, so nothing is being returned in the query.

Add the following line to your test class.
 
PStg.Operation_Type__c = 'Insert';

Hope that helps,

Clint

All Answers

ClintLeeClintLee
Hi Gaurav,

The query in your batch class has WHERE Operation_Type__c = 'Insert'.  

It doesn't look like you added an Operation Type when you created the record in your test class, so nothing is being returned in the query.

Add the following line to your test class.
 
PStg.Operation_Type__c = 'Insert';

Hope that helps,

Clint
This was selected as the best answer
Gaurav AgnihotriGaurav Agnihotri
Yes, it did help.
Also, I used  @istest (seealldata=true)

Now, I am getting 100 % code coverage.. woohoo!!