[SalesForce] Assertion failure that a null pointer exception is caught

I am doing some test code right now. In my Apex code I have a method that try-catches a DMLException and afterwards does a general Exception catch.

In my test code I am successfully managing to test both(they come out as success), however salesforce doesn't acknowledge the test for the general exception.

Do you have any ideas? Thank you!

Here's my method code:

    public void createTimeSheet() {
        errorMsg = '';
        TimeSheet__c newTimeSheet = new TimeSheet__c(
            Date__c = date.valueOf(newTimeSheetDate),
            Status__c = 'New',
            Employee__c = [SELECT Id FROM Employee__c WHERE Name=:EmployeeName].Id
        );
        try {
            insert newTimeSheet;
        //catching the DML exceptions first
        } catch(DmlException e) {
            errorMsg = e.getDmlMessage(0);
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,errorMsg));
        //catching all other exceptions
        } catch(Exception e) {
            errorMsg = e.getMessage();
            ApexPages.addmessage(new ApexPages.message(ApexPages.severity.ERROR,errorMsg));
        }
}

And here's my test method code:

public static testMethod void createTimeSheetNullPointerFail_test() {
        init();

        cont.EmployeeName = testEmployeeName;
        cont.tslist = testTsList;

        test.startTest();
            cont.createTimeSheet();
        test.stopTest();
        System.assert(cont.errorMsg.contains('System.NullPointerException: Attempt to de-reference a null object'), cont.errorMsg);
    }

Best Answer

Exceptions have a type (e.g. "NullPointerException") and a message (e.g. "Argument cannot be null") and perhaps most usefully of all a stack trace (the line number and class name that the exception was thrown from and the calling line numbers and class names). If you are going to add error handling logic for random programming errors then I recommend that you capture all 3 pieces of information as otherwise you are making the process of finding and fixing the error harder than it needs to be.

See the Common Exception Methods that are available.

It is often be better to not add logic that tries to handle programming errors. For example, in a Visualforce controller class the default error handling works well and the stack trace detail can be obtained by turning on "Development Mode" for a User and reproducing the error using that User.

Running this using "Execute Anonymous":

try {
    Date.valueOf((String) null);
} catch (Exception e) {
    System.debug('>>> ' + e.getMessage());
}

confirms that the error message string will only contain "Argument cannot be null" (though FYI the exception thrown is of type "NullPointerException").

Related Topic