+ Start a Discussion
davidpadburydavidpadbury 

Testing addError outside a trigger

I am reusing the same validation code in several triggers, so instead of duplicating this for each I have refactored it into a class which they all call. When testing this class in isolation the sObject.addError method does not throw a DMLException. This is to be expected as the documentation states that exceptions are only thrown in the context of a trigger.

 

My question is, are there any other ways of testing that the addError method has been called?

 

I've put together an example to demonstrate this issue...

 

 public class ErrorExample {
    
    public static void addAnError(sObject obj) {
        obj.addError('test');
    }
    
    static testmethod void addAnError_alwaysAddsAnError() {
        Boolean hasFailed = false;
        
        Account a = new Account ( Name = 'Test' );
        insert a;
        
        try {
            ErrorExample.addAnError(a);
        } catch (DMLException e) {
            hasFailed = true;
        }
        
        // THIS ASSERT FAILS
        System.assert(hasFailed);
    }
    
}

mtbclimbermtbclimber

Yes. You can use the messaging utility methods from Visualforce to test for this condition.

 

For example:

 

 

public class ErrorExample { public static void addAnError(sObject obj) { obj.addError('test'); } static testmethod void addAnError_alwaysAddsAnError() { Account a = new Account ( Name = 'Test' ); ErrorExample.addAnError(a); // THIS ASSERT PASSES System.assert(ApexPages.hasMessages()); } }

 

Check out the Visualforce developer guide for more information.