3

I have following situation : I have TOO MANY try-catch written in my Apex Class (TriggerHandler class) Where I am not able to get coverage for all of them.

APEX CLASS :

public virtual override void onAfterUpdate(boolean isReEntry, 
                      List<SObject> oldObjects, 
                      List<SObject> updatedObjects, 
                      Map<ID, SObject> objectMap,
                      Map<ID, SObject> oldobjectMap){

   try{

   }catch(Exception e){  
    NEED COVERAGE   (GOT coverage for this only by doing following..)
   }
   try{

   }catch(Exception e){  
    NEED COVERAGE 
   }
   try{

   }catch(Exception e){  
    NEED COVERAGE 
   }
  try{

   }catch(Exception e){  
    NEED COVERAGE 
   }


}

* By doing following in TEST CLASS I got First catch block coverage which is there onAfterUpdate method -- BUT not for other following it :

...

try{
   Controller.onAfterUpdate(False,null,null,null,null);
}Catch(Exception e){}

....
  • Any Help
  • Any Suggestion (Except - Write code in such way which will cause an error in class) --> In my case this is quite not possible.
2

@sfdcfox has written extensively on this -- depends on what exception you are catching (for some, you can construct the mocked test data to force an exception, for others, not) and whether it is worth bothering to to get code coverage for the exceptions. I know I have sometimes done the following in a multistep DML method

String step;
try {
    step = '00 - do dml X';
    insert (or update or delete) some objList;

    step = '01 - do dml Y';
    insert (or update or delete) some otherObjList;
}
catch (Exception e) {
   // do something (throw exception to caller perhaps) 
   // but at least surface e.getMessage() and value of step variable
}

This way, if all you are worried about is code coverage, the # lines of catch block is small and perhaps in your mocked data, you can easily inject an exception to occur

If, on the other hand, each catch block is doing something more complex like a partial rollback or some complex retry logic, you'll need to break the catch block bodies into separate methods, each testable on its own

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.