I wrote a test class for a Batch Apex Class that has a chain of another class in the Finish method. I tried the following approach, but it still does not cover the lines in the Finish method. Is there a way for me to change the test class in order to get 100% coverage?
Here is my Batch Apex Class:
@isTest(SeeAllData = false)
private class BM_StageToLive_TargetPackedProd_Test{
@isTest
private static void TestStageToLive_TargetPackedProd(){
System.Test.startTest();
BM_FC_Mgmt__c[] fcs = BM_StageToLive_TestDataFactory.createFCWithCrews(1, 5);
List<BM_PPackingProductivity_Staging__c> ppsListToInsert = new List<BM_PPackingProductivity_Staging__c>();
for (BM_FC_Mgmt__c fc : fcs){
BM_PPackingProductivity_Staging__c newPPS = new BM_PPackingProductivity_Staging__c();
newPPS.BM_PPS_FC__c = fc.Id;
newPPS.BM_PPS_Date__c = Date.newInstance(2023, 01, 01);
newPPS.BM_PPS__c = 150.1;
ppsListToInsert.add(newPPS);
}
insert ppsListToInsert;
//test the class with the available data
Date startDate = Date.newInstance(2023, 01, 01);
Date endDate = Date.newInstance(2023, 01, 01);
BM_StageToLive_TargetPackedProd_Batch newBatch = new
BM_StageToLive_TargetPackedProd_Batch();
newBatch.startDate = startDate;
newBatch.endDate = endDate;
Database.queryLocator ql = newBatch.start(null);
newBatch.execute(null, ppsListToInsert);
newBatch.Finish(null);
// newBatch.startDate = startDate;
// newBatch.endDate = endDate;
// Database.executeBatch(newBatch, 1);
System.Test.stopTest();
}
}
Here is my Test Class for the Finish Method:
global void finish(Database.BatchableContext dbc){
if (!Test.isRunningTest()){
BM_StageToLive_EstimatedStock_Batch obj3 = new BM_StageToLive_EstimatedStock_Batch();
obj3.startDate = startDate;
obj3.endDate = endDate;
Database.executeBatch(obj3, 30);
}
}
Thank you in advance !
finish
method to be tested, the problem is that everything it does is in an if condition that is false when running a test. Do you know why it doesn't run in a test? Can you just remove the if condition?Database.executeBatch
rather than simply using the approach you illustrate for testingfinish
(which is direct invocation of the method(s) in question).