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
OcoBriOcoBri 

Trigger and Test Class works in Sandbox but not in Production

Hi,

I've writen a trigger and test class that work well in the Sandbox, but when I attempt to deploy in Production, the test fails.
Whenever a "Worker" (custom object) is created, I need to also create a matching Contact.  I'm not concerned with creating duplicates at this point.  We use the Nonprofit Starter Pack.

Trigger:
trigger NewContactforWorker on VanaHCM__Worker__c (after insert) {
	List<Contact> conList = new List<Contact>();
    for (VanaHCM__Worker__c wkr : trigger.new) {
        Contact a = new Contact(
            Worker__c = wkr.Id, 
            FirstName = wkr.VanaHCM__First_Name__c,
            LastName = wkr.VanaHCM__Last_Name__c, 
            QSAC_external_id__c = wkr.VanaHCM__External_Worker_ID__c,
            npe01__Preferred_Email__c = 'Personal',
            npe01__PreferredPhone__c = 'Home', 
            npe01__Primary_Address_Type__c = 'Home');
        conList.add(a);
    }
    if(conlist.size()>0){
try{
    insert conList;
    system.debug('inserted new contact');
}catch(DMLException e){
System.debug('Error trying to insert new contact(s). Alert the media!');
}
}
}
And the test class:
@istest public class WorkerToContactTestClass {
    private static testmethod void TestWorkerToContact(){
        VanaHCM__Worker__c testwrkr = new VanaHCM__Worker__c(VanaHCM__First_Name__c = 'Flip', 
                                                             VanaHCM__Last_Name__c = 'Nahasapeemapetalan', 
                                                             VanaHCM__External_Worker_ID__c = 'X1');
        insert testwrkr;
        
        list<contact> foundWorkers = [SELECT Id FROM Contact WHERE QSAC_external_id__c = 'X1'];
        system.assertEquals(foundWorkers.size()>0, TRUE);
    }

Can anyone help?

Thank you

UdhayaUdhaya
I believe select query returns 0 rows as the test method doesn't have access to the organization data. Hence, try to insert the contact before validating the assertion(system.assertEquals(foundWorkers.size()>0, TRUE))
OcoBriOcoBri
I'm not sure I understand.  The contact should be inserted by the trigger right after I insert the test Worker (line 06 in the test class).
Kiran  KurellaKiran Kurella
You can try the following:

1. Make sure the Contact validation rules in Sandbox match the Production.
2. Update try/catch section in your trigger as follows. We should never ignore a failed transaction. You can simply throw the error back to the user with a throw statement.

If the problem still exists then post the error details (with line no).

try {

 // your existing code 

} catch(DMLException e) {
   system.debug('Error trying to insert new contact(s). Alert the media!');
   throw e;
}