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 trigger on Opportunity and managed to test it and it ran smoothly and even tried it out on the sandbox and everything ran fine. I then decided to use addError() along with the trigger.

if(Trigger.isBefore){   // Error checking, will verify that a contract child does not exist, will also verify that if any variables are null. 
    for(Opportunity verifyOpp: oppsFromDB){             
      if(verifyOpp.service_Contracts__r.size() != 0)
      {
         String x = 'Hi';
         trigger.newMap.get(verifyOpp.Id).addError(x);
      }
    }
   .....

The exception error I get is : System.DmlException: Update failed. First exception on row 0 with id 006.....; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, HI:[]

Just an FYI the List I am doing a for loop works perfectly fine on the Trigger.isAfter bit, so I am pretty certain it isn't in the eternal loop.

Any help would be greatly appreciated.

share|improve this question

1 Answer 1

up vote 5 down vote accepted

This is the appropriate behavior, since you are adding an error to the record. In your test class you need to add the insert within a try/catch statement, and add in assertion in the catch statement verifying the error message received is the error message you passed in.

Hope this helps!

share|improve this answer
    
Thanks jonny, I will try and get that to work ! –  jnoel10 Feb 21 '13 at 21:45
1  
If it works for you don't forget to mark this as the answer so other people know as well! –  jonnybro Feb 21 '13 at 22:50
    
Thanks jonnybro, sorry for the delay I finally managed to test this and you are correct the try/catch statement worked beautifully. Thanks again –  jnoel10 Feb 25 '13 at 15:09

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.