I have below code to coverage :

 public static list<Contact> getContactsByAccountId(Id accountId, Id contactId){
            return [SELECT Id, firstName, LastName, Email, Phone
                    FROM Contact 
                    WHERE AccountId = :accountId 
                    AND Id!=: contactId];
        }catch(Exception e){
            system.debug('Exception in getContactsByAccountId: ' + e.getMessage());
            return null;

how to cover catch block in test class?


Do you have a reason to expect an exception to be thrown from that query? I can't think of any reason why there ever should be an exception thrown other than governor limit ones that can't be caught anyway. Typically you will just get no rows returned if the where condition isn't met.

So rather than trying to cover the catch block remove it.

Couple of other points:

  • if it really made sense to just log the exception then instead of returning null returning and empty list using return new List<Contact>{}; would be kinder to the calling code
  • if there was a valid exception, remember that you can choose to handle it in other layers of your software than the layer it immediately happens in i.e. you can let it propagate out to the calling code and so put all the exception handling in one place such as the the controller action rather than in multiple places

There are plenty of gotchas with exceptions. See the detailed points in for example Java theory and practice: The exceptions debate.

| improve this answer | |
  • Thanks Keith, I have to create test class where i cannot remove/add any original code, You are absolutely right that if it is returning null, there is no seance to write the catch block, but here we have to cover a code which is written by someone else :( – Bharat Sep 22 '14 at 9:52
  • @Bharat You have my sympathy. I think you should raise a bug on that code then saying that those lines of code are untestable (and probably should not be there). Concocting some way to actually cover them in your test is just adding more questionable code on top of some questionable code. Then just test the part you can test using clean test code. – Keith C Sep 22 '14 at 9:57

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.