+ 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) {
            if(objList!= null && objList.size() > 0 ){
                delete objList;
        catch(Exception ex){
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.
    private static void testBatch(){
        OBJ__c obj = new OBJ__C(YOUR required fields);
insert obj;
        Id batchId = Database.executeBatch(new YOUR BATCH CLASS NAME ());
        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.