Take the 2-minute tour ×
Salesforce Stack Exchange is a question and answer site for Salesforce administrators, implementation experts, developers and anybody in-between. It's 100% free, no registration required.

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 ?

share|improve this question
2  
You could wrap your dml in a try-catch and assert the error message in the catch block. –  techtrekker Jan 19 '13 at 1:35
add comment

2 Answers

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!

share|improve this answer
add comment

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.

share|improve this answer
    
I want to check error without record insertion. –  S.Sharma Jan 18 '13 at 12:25
    
You can only get the errors after you insert/update/delete/upsert, as far as I know. –  Ivo Rocha Jan 18 '13 at 12:39
add comment

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.