Another Salesforce blog!!!

Salesforce, Apex

How to test for an exception(‘addError’) in a Trigger

I have a trigger, which detects error conditions and feeds errors to the class or field.
This gives a nice result interactively, in the GUI. But how do I write test code to catch these errors ? Is there a System.AssertException(), or the equivalent ?

The idea is to:

a. Write code in the test class that will cause the trigger to ‘addError()’.
b. Surround the above test class code with try – catch.
c. Assert that an exception is thrown and that the exception message is the same one you created with ‘addError()’.

if(myRecord.MyField == some value) {
   myRecord.addError('My Error Message');
Test Class: 
    MyRecord.MyField = a value that will cause an error; 
    update MyRocord;
    throw new MyException('An exception should have been thrown by the trigger but was not.'); // 1. If we get to this line it means an error was not added and the test class should throw an exception here. 2. MyException class extends Exception.
catch(Exception e)
    Boolean expectedExceptionThrown =  e.getMessage().contains('My Error Message')) ? true : false;
    System.AssertEquals(expectedExceptionThrown, true);

or you can also use something like this:

System.Assert(e.getMessage().contains('My Error Message'));

Leave a Reply

Your email address will not be published. Required fields are marked *