function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Vishal Tiwari 36Vishal Tiwari 36 

How to cover exception in execute method for batches in the test classes?

 global void execute(Database.BatchableContext BC, List<OBJ__c> objList) {
        try{
            if(objList!= null && objList.size() > 0 ){
                delete objList;
            }
        }
        catch(Exception ex){
            System.debug('Exception');
        }
    }
Agustin BAgustin B
Hi Vishal, you can use Database.ExecuteBatch(new YOUR-BATCH-CLASS-NAME());
Create a record for OBJ__c before using execute batch that will be retrieved on your start method.
Validate that whatever you have on your start method query is returning data.
@IsTest
    private static void testBatch(){
        OBJ__c obj = new OBJ__C(YOUR required fields);
insert obj;
        Test.startTest();
        Id batchId = Database.executeBatch(new YOUR BATCH CLASS NAME ());
        Test.stopTest();
        System.assertEquals(0,[SELECT IdFROM OBJ__c].size());
    }


if it helps please like and mark as correct,  as it may help others.
 
Vishal Tiwari 36Vishal Tiwari 36
Hi @Agustin, Thank you for the answer. I have tried doing that but that is not covering the catch block. I believe I have to raise an exception but I'm not sure how to do that.