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 ?

  • 2
    You could wrap your dml in a try-catch and assert the error message in the catch block. Jan 19, 2013 at 1:35

2 Answers 2


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!

  • Note: ApexPages.getMessages() works in VisualForce pages only, in case that is not clear.
    – Ixalmida
    Nov 15, 2018 at 18:24

You can use Database.insert(), Database.update(), etc.. Then it will return a Database.SaveResult and if it have errors you can get them like this:

Database.SaveResult [] updateResult = Database.update(records, false);  
for (Database.SaveResult r : updateResult){  
  if (!r.isSuccess()){  
    for (Database.Error e : r.getErrors()){  
      // errors here  

Hope this help you.

  • 2
    I want to check error without record insertion.
    – S.Sharma
    Jan 18, 2013 at 12:25
  • You can only get the errors after you insert/update/delete/upsert, as far as I know.
    – Ivo Rocha
    Jan 18, 2013 at 12:39

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .