0

When you create a Barrel, a Filling is also created. Is there any chance to make a fake error in unit test between Barrel and Filling to crush the upsert process and cover the catch block?

Helper:

public void insertFilling(List<Barrel__c> createdBarrels){
List<Filling__c> fillingsToInsert = new List<Filling__c>();
for(Barrel__c barrel : createdBarrels){
    if(barrel.FinishDateTime__c >= Date.TODAY()){     
        fillingsToInsert.add(
            new Filling__c(Barrel__c = barrel.Id, Barrel_ExternalID__c = barrel.Id)
        );
    }
}
if(!fillingsToInsert.isEmpty()){
    try{
        upsert fillingsToInsert Barrel_ExternalID__c;
    //I want to cover this part:
    } catch(Exception e){
        //email error notification
    }
}
}

Trigger:

trigger BarrelTrigger on Barrel__c (after insert) {
  TriggerHelper helper = new TriggerHelper();
  helper.insertFilling(Trigger.new);
}

Test:

    @isTest static void testBarrelInsertException(){
    Barrel__c barrel = new Barrel__c(
        Name = 'TestBarrel',
        Opportunity__c = null, //required field
        FinishDateTime__c = DateTime.NOW().AddDays(1)
    );
    //But I even can't insert it. I'm getting the 'REQUIRED_FIELD_MISSING' error:
    insert barrel;
    //And still no coverage.
}
  • If you ever run into a situation where you really need to cause an exception for a unit test, using dependency injection is going to be your best option (developer.salesforce.com/blogs/2019/07/…). That way you can use a testing version of one of your dependencies to cause it to always fail or throw a specific exception. – nbrown Mar 11 at 13:15
  • Thank you!...... – Dan Dan Mar 11 at 13:33
3

The only way to cover a catch is if you cause your code inside the try to fail.

In your case you should get rid of the try/catch because it will never fail (or, let's say you introduce a new validation rule on the Filling it will always fail and you will need to change the trigger).

There another good answer that discuss the benefits of catching: When do we really need try/catch?

| improve this answer | |

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.