+ Start a Discussion
Jack VolkovJack Volkov 

How do you write a test method for unknown/unexpected errors?

The logic in an apex trigger and apex class has been written to account for all known errors so that an exception will not be thrown.  But for those unknown errors that will occassionally popup, exception error handling has been written in order to better understand what caused the exception.

How can test coverage be provided for the exception handling example below if it is not yet known how an error can be caused in the first place?
try {
        // calling an apex class method so the logic runs
    } catch (System.Exception e) {
        trigger.new[0].addError('There was an error caused by an apex trigger calling an apex class.  Please contact your administrator.    '
        						+ ' *** exception type: ' + e.getTypeName()
        						+ ' *** cause: ' + e.getCause()
        						+ ' *** line number: ' + e.getLineNumber()
        						+ ' *** stack trace: ' + e.getStackTraceString());
        // send an email with error details
        Messaging.SingleEmailMessage mail=new Messaging.SingleEmailMessage();
        String[] toAddresses = new String[] {'apexdevs@example.com'};
        mail.setToAddresses(toAddresses);
        mail.setReplyTo('apexdevs@example.com');
        mail.setSenderDisplayName('Apex Error Message');
        mail.setSubject('Error from Org : ' + UserInfo.getOrganizationName());
        mail.setPlainTextBody(e.getMessage());
        system.debug(' Exception message displayed for the user: ' + e.getMessage());
    }

 
James LoghryJames Loghry
The answer is it depends on your code or trigger.  In my test classes, I'll generally have 1 easy path test, where it's a simple successful scenario.  Then, I'll have multiple other tests for error conditions (empty string and null values or combinations thereof) in addition to seperate classes for exceptions like what you're showing above.

In the separate exception test case, you'll need to figure out how to invoke the exception.  Perhaps it's bad data or intentionally missing a required value.  Perhaps it's leaving a null value to throw a NullPointerException.  You'll need to trick the method and the logic at this comment:
// calling an apex class method so the logic runs
into throwing an exception to cover that catch block.  If you can't find anything that works as far as throwing an exception, you can use a last resort hack, You would create a throwException member variable in your Apex class (or a field on the object where the  trigger fires).  If that variable is set and Test.isRunningTest is true inside your try block, then you manually construct and throw an exception in Apex.

Once you have the catch block covered, you can use Limits.getLimitEmailInvocations() to calculate the difference in email invocations to determine if an email was sent out.

Hope that helps.