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 :)
c.MailingCountry != null && c.MailingCountry != ''
can be substituted withString.isNotBlank(c.MailingCountry)