+ Start a Discussion
Skip KSkip K 

How to test apex exception

I'm using addError in a trigger to show an error when a user tries to enter a weekend day into a date field. When I test this negative condition the test fails. How do I test it so that running the test actually passes?
if (dt.format('E').equals('Sun')||dt.format('E').equals('Sat')) {
                try {
                    t.Close_Date__c.addError('Close Date must occur on a weekday.');
                } catch (Exception e) {
                    Boolean expectedExceptionThrown =  e.getMessage().contains('Close Date must occur on a weekday.') ? true : false;
                    System.AssertEquals(expectedExceptionThrown, true);

Best Answer chosen by Skip K
Skip KSkip K
OK. Duh! I had the try/catch in my trigger instead of my test class.