How to check if any error has been added to a record?

I have created a method which is being called through a trigger. I am adding error to a record if it is a duplicate one using ‘addError()’ method .

Now , I want to cover this method in my test class. How Can I check that on which records , error has been added ?

Answer

The addError methods in a Visualforce context will also add to the Apex Page messages collection, which you can access via the ApexPages.getMessages method.

When used in Visualforce controllers, the generated message is added to the collection of errors for the page.

    Test__c testRecord = new Test__c();
    testRecord.addError('Some error');
    testRecord.A_Number__c.addError('Field error');
    for(ApexPages.Message message : ApexPages.getMessages())
        System.debug(message.getComponentLabel() + ' : ' + message.getSummary());

The following results in…

20:03:00:155 USER_DEBUG [8]|DEBUG|null : Some error

20:03:00:156 USER_DEBUG [8]|DEBUG|A Number : Field error

Unfortunatly the record that generated the error is not availble.

Finally you might also be interested in the ApexPages.hasMessages method as well.

Hope this helps!

Attribution
Source : Link , Question Author : S.Sharma , Answer Author : Community

Leave a Comment