[SalesForce] Before Insert Trigger not updating field

I have a before insert trigger to update a custom field on the Contact object, Region__c. Debugging confirms that the field is set to the correct value on the sObject, but both the test asserting the field is set to the correct value and manually creating a new Contact shows that the field is still blank (after the transaction has completed.) However, the value is set correctly if the record is only updated (not inserted.) The trigger doesn't seem to be throwing an error but the field is still blank rather than the correct value. I've also confirmed the following:

  • There are no other triggers writing to the field on the Contact
    object.
  • There are no workflow rules writing to the field on the
    Contact object.

Trigger:

trigger SetRegion on Contact (before insert, before update) {
    for (Contact c :  Trigger.New){
        try {
            if (c.MailingCountry != null && c.MailingCountry != ''){

                //Outputs: 'Angola'
                System.Debug(c.MailingCountry);

                //Returns: 'Africa' (Correct)
                c.Region__c = RegionHelper.GetRegion(c.MailingCountry);

                //Outputs: 'Africa' (Correct)
                System.Debug(c.Region__c);
            }
        }
        catch(Exception e){
            System.Debug('Error setting region.');
        }
    }
}

Failing Test (Also fails when creating record manually):

@isTest
public with sharing class TestSetRegion {
    public static testMethod void TestSetRegionContactUpdate(){     
        Contact c = new Contact(LastName='x',MailingCountry='Angola');
        insert c;
        System.assertEquals('Africa',c.Region__c);
        delete c;
    }       
} 

Test result: "System.AssertException: Assertion Failed: Expected: Africa, Actual: null"

Any insight would be appreciated, hoping this is just a newbie mistake 🙂

Best Answer

well, one issue is with your testmethod - you need to requery the Contact to get the value set in the trigger

    Contact c = new Contact(LastName='x',MailingCountry='Angola');
    insert c;
    Contact cRes = [select id, region__c from Contact where id = :c.id];
    System.assertEquals('Africa',cRes.Region__c);

also, although not related to your issue per se, try-catch in your before trigger needs to do an addError on the offending record, unless eating the error is intended.

Related Topic