function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
AlbertoKiteAlbertoKite 

Deploy trigger with addError

I'm trying to deploy a trigger on a production environment, but when I use "addError" method and run a test on that line I got the error (as I expect) but I cannot deploy it.
 
Code:
trigger Share_upd on TI_Shares__c (before update) 
{
 List <TI_Shares__c> shares2Update = new List <TI_Shares__c>();
 for (Integer i = 0; i < Trigger.old.size(); i++) 
 {
  TI_Shares__c iOld = Trigger.old[i];
  TI_Shares__c iNew = Trigger.new[i];
  Boolean checkError = false; 
  
  if (iNew.Share_type__c!=iOld.Share_type__c) {iNew.Share_type__c.addError('Share type cannot be modify!! If you need to modify it delete the record and create a new one'); checkError=true;}
    if (checkError==false)
  {
...

 
 
Run Failures:
  testSharesTrigger.testSharesInfo System.DmlException: Update failed. First exception on row 0 with id a0A200000022Z6aEAE; first error: FIELD_CUSTOM_VALIDATION_EXCEPTION, Share type cannot be modify!! If you need to modify it delete the record and create a new one: [Share_type__c]
 
 
Any Ideas??
I could avoid to run a test that simulate that error but I wouldn't exclude any line of code in my test set.
 
Thanks
JonPJonP
You need to use a try/catch block to catch the exception.  In fact, you should add an assert that ensures the exception is thrown when it's expected.
AlbertoKiteAlbertoKite

You mean that in my testMethod I must use a try catch when I have to test this situation ?

Could you explain me better?

Thanks for your help?

JonPJonP
Yes, exactly--your test method should contain the try/catch.  Here's pseudocode, which might veer into Java in places, but it illustrates the technique:

Code:
public class demo
{

  public static double divide(double dividend, double divisor)
  {
     if (divisor == 0) {
        throw new Exception('divide by 0 error');
     }
     return dividend / divisor;
  }

  static testMethod testDivideByZero()
  {
     boolean exceptionThrown = false;
     try {
        divide(10.0, 0.0);
     } catch (Exception e) {
        System.assertEquals('divide by 0 error', e.getMessage());
        exceptionThrown = true;
     }
     // if no exception was thrown, you never get to the catch block,
// so you need a safeguard:
System.assertEquals(true, exceptionThrown); } }

 

AlbertoKiteAlbertoKite
OK, Thanks a lot for your suggestion.