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
Nicholas Sewitz 9Nicholas Sewitz 9 

After Update Test Class Not Triggering After Update TriggerHandler

Hi!

I have an child object `Lifecycle_History__c` to `Contact`. Everytime the field`Contact.lifecycle__c` is changed I create a new `Lifecycle_History__c` object that captures some data from the `Contact`. Essentially it is a snapshot object for reporting purposes. 

I wrote some Apex for this and when I change the lifecycle on a contact in the sandbox everything works as expected. For example if a create a new contact with a `lifecycle__c` then there should be 1 related `Lifecycle_History__c` object.  If I edit that contact and change the `lifecycle__c` field, then there are 2 `Lifecycle_History__c` objects.

However in my Apex Test `testcontactUpdate()` my assertion that there should be 3 `Lifecycle_History__c` is failing and saying there is only 1. When I debug I can see that when I run the test it's the `lifecycle__c` on `c` is not updating even after I call update and in turn not triggering the creation of a new `Lifecycle_History__c`.

Apex Trigger:
 
trigger ContactTrigger on Contact (after insert, after update,after delete){
    TriggerSupport__c  objCustomSetting= TriggerSupport__c.getInstance('ContactTrigger');
    if(objCustomSetting.TriggerOff__c == false) {
        return;
    }
    else if(Trigger.isAfter)
    {
        if(Trigger.isUpdate){
            if(LeadTriggerHandler.isFirstTimeAfter){
                LeadTriggerHandler.isFirstTimeAfter = false;
                System.debug('inafterupdatetrigger');
                ContactTriggerHandler.afterUpdate(Trigger.New, Trigger.oldMap); }
        }
        else if(Trigger.isInsert){
            ContactTriggerHandler.afterInsert(Trigger.New);
        }
        else if (Trigger.isDelete){
            ContactTriggerHandler.afterDelete(Trigger.Old);
        }
    }
}



Apex Class:
public with sharing class ContactTriggerHandler {
 //   public static Boolean isFirstTimeAfter = true;
/**
* after delete handler for merging patrons
 */  
    
    public static void afterDelete(List<Contact> deletedcontacts) {
        Map<Id,Contact> contactidmap = new Map<Id,Contact>();    // this is a map of deleted contact id to merged contact map

        
        
        for (Contact c : deletedcontacts) {
            
            Database.DMLOptions dlo = new Database.DMLOptions();
            dlo.EmailHeader.triggerUserEmail = false;
            dlo.EmailHeader.triggerAutoResponseEmail = false;
            c.setOptions(dlo);   
            
            
            if (c.MasterRecordId != null) {
                // this is a merge, setup a map of old, new id
                contactidmap.put(c.MasterRecordId,c);
                System.debug('contact map' + contactidmap);
                System.debug('contact id' + c.Id );
                System.debug('master record' + c.MasterRecordId);
            }
        }
        
        if (!contactidmap.keySet().isEmpty()) {
            // now loop through all the patrons looking up to the old contact and reassign to new contact
            List<Patron__c> patlist = [select Id,Contact__c from Patron__c where Contact__c in :contactidmap.keySet()];
           // List<Lifecycle_History__c> mqllist = [select Id,Contact__c from Lifecycle_History__c where Contact__c in :contactidmap.keySet()];

            
            for (Patron__c pat : patlist) {
                
                Database.DMLOptions dlo = new Database.DMLOptions();
                dlo.EmailHeader.triggerUserEmail = false;
                dlo.EmailHeader.triggerAutoResponseEmail = false;
                pat.setOptions(dlo);   

                pat.Contact__c = contactidmap.get(pat.Contact__c).MasterRecordId;
               
            }
            
         /*   for (Lifecycle_History__c mql : mqllist) {
                
                Database.DMLOptions dlo = new Database.DMLOptions();
                dlo.EmailHeader.triggerUserEmail = false;
                dlo.EmailHeader.triggerAutoResponseEmail = false;
                mql.setOptions(dlo);   

                mql.Contact__c = contactidmap.get(mql.Contact__c).MasterRecordId;
               
            }*/
            System.debug('patron list ' + patlist);
            update patlist;
           // System.debug('patron list ' + mqllist);
        //    update mqllist;
            dupcheck.dc3Api api = new dupcheck.dc3Api(); 
            api.domerge(patlist);
    }
    }
   
   
   
    /**
* after insert handler for attaching patron and applications
* @param newcons [description]
*/
    public static void afterInsert(List<Contact> newcons) {
        Set<Id> cons = new Set<Id>();    // contacts
        for (Contact c : newcons) {
            cons.add(c.Id);
        }
        
        // query more information on contacts for patron
        // loop through contacts and create patrons
        List<Patron__c> newpatlist = new List<Patron__c>();
        List<Lifecycle_History__c> newlifecyclehistorylist = new List<Lifecycle_History__c>();
        for (Contact c : [Select Id,
                          Marketing_Qualified_Detail_Most_Recent__c,
                          Marketing_Qualified_Reason_Most_Recent__c,
                          Datetime_Marketing_Qualified_Most_Recent__c,
                          Datetime_Sales_Accepted_Most_Recent__c,
                          Datetime_Sales_Qualified_Most_Recent__c,
                          Datetime_Recycled_Most_Recent__c,
                          Datetime_Disqualified_Most_Recent__c,
                          Datetime_Won_Most_Recent__c,
                          Datetime_Lost_Most_Recent__c,
                          Recycled_Reason__c,
                          Recycle_Until_Date__c,
                          Disqualified_Reason__c,
                          Account.AccountSource,
                          utm_source_Most_Recent__c,
                          utm_campaign_Most_Recent__c,
                          utm_content_Most_Recent__c,
                          utm_medium_Most_Recent__c,
                          utm_term_Most_Recent__c,
                          OwnerId,
                          Email,
                          Phone,
                          Count_of_Patron_Contacts__c,
                          Created_via_Conversion_Process__c,
                          lifecycle__c,
                          Abbreviated_Channel__c,
                          Anything_else__c,
                          Application_Mode__c,
                          Account.Name,
                          How_did_you_learn_about_Artsy__c,
                          Interests__c,
                          AccountId,
                          Learned_from_detail__c,                                                                   
                          Name,
                          Datetime_of_Partnership_Application__c
                          from Contact where Id in :cons])
            if (c.Created_via_Conversion_Process__c == FALSE) {
               
                Patron__c pat = new Patron__c();
                PatronUtil.populatePatronfromContact(pat, c);
                newpatlist.add(pat);
                
            if(c.lifecycle__c != null) {
                    Lifecycle_History__c lifecyclehistory = new Lifecycle_History__c();
                    LifecycleUtil.populatelifecyclefromContact(lifecyclehistory, c);
                    newlifecyclehistorylist.add(lifecyclehistory);
                }
        }
        
        if (!newpatlist.isEmpty()) {
            insert newpatlist;
        }
        
        if (!newlifecyclehistorylist.isEmpty()) {
            insert newlifecyclehistorylist;
            System.debug('inclassinsert');
            System.debug(JSON.serializePretty(newlifecyclehistorylist));
        }
        
    }
    
    /*
* update children patron records after contact updates
* @param newconmap [description]
* @param oldmap [description]
*/
    public static void afterUpdate(List<Contact> updatedcons, Map<Id,Contact> oldmap) {
        System.debug('inafterupdatehandler');
        // select all necessary data
        Map<Id, Contact> updatedconmap = new Map<Id,Contact>([Select  Id,
                                                                      Marketing_Qualified_Detail_Most_Recent__c,
                                                                    Marketing_Qualified_Reason_Most_Recent__c,
                                                                    Datetime_Marketing_Qualified_Most_Recent__c,
                                                                    Datetime_Sales_Accepted_Most_Recent__c,
                                                                    Datetime_Sales_Qualified_Most_Recent__c,
                                                                    Datetime_Recycled_Most_Recent__c,
                                                                    Datetime_Disqualified_Most_Recent__c,
                                                                      Datetime_Won_Most_Recent__c,
                                                                      Datetime_Lost_Most_Recent__c,
                                                                    Recycled_Reason__c,
                                                                      Recycle_Until_Date__c,
                                                                    Disqualified_Reason__c,
                                                                    Account.AccountSource,
                                                                    utm_source_Most_Recent__c,
                                                                    utm_campaign_Most_Recent__c,
                                                                    utm_content_Most_Recent__c,
                                                                    utm_medium_Most_Recent__c,
                                                                    utm_term_Most_Recent__c,
                                                                    OwnerId,
                                                                    Email,
                                                                    Phone,
                                                                    Count_of_Patron_Contacts__c,
                                                                      Created_via_Conversion_Process__c,
                                                                    lifecycle__c,
                                                                    Abbreviated_Channel__c,
                                                                    Anything_else__c,
                                                                    Application_Mode__c,
                                                                    Account.Name,
                                                                    How_did_you_learn_about_Artsy__c,
                                                                    Interests__c,
                                                                    AccountId,
                                                                    Learned_from_detail__c,                                                                   
                                                                    Name,
                                                                    Datetime_of_Partnership_Application__c
                                                                    from Contact where Id in :updatedcons]);

        // find patrons
        List<Patron__c> patstoupdate = [Select Contact__c from Patron__c where Contact__c in :updatedconmap.keySet()];
        
        for (Patron__c pat : patstoupdate) {
            
            PatronUtil.populatePatronfromContact(pat, updatedconmap.get(pat.Contact__c));
        }
        
        update patstoupdate;
       
        
        for (Contact c : updatedcons) {         
            System.debug('inafterupdatehandlerloopbeginning');
            System.debug(c.lifecycle__c);
            System.debug(oldMap.get(c.Id).lifecycle__c);
            if (c.lifecycle__c != oldMap.get(c.Id).lifecycle__c) {
                // find lifecycles
                List<Lifecycle_History__c> lifecyclestoinsert = new List<Lifecycle_History__c>();
                System.debug('inafterupdatehandlerloop');
                for (Id contactid : updatedconmap.keySet()) {
                    Lifecycle_History__c lifecyclehistory = new Lifecycle_History__c();
                    LifecycleUtil.populateLifecyclefromContact(lifecyclehistory, updatedconmap.get(contactid));
                    lifecyclestoinsert.add(lifecyclehistory);
                    System.debug('inafterupdatehandlerloop2');
                }
                if (!lifecyclestoinsert.isEmpty()) {
                    insert lifecyclestoinsert;
                    System.debug('inclassupdate');
                    System.debug(JSON.serializePretty(lifecyclestoinsert));
                        
                }
            }
            
        }             
    }
}


Apex Test:
@isTest
private class ContactTriggerHandlerTest {
    
        @isTest static void testContactUpdate() {
        // Create custom setting
        TriggerSupport__c ts = new TriggerSupport__c();
        ts.Name='ContactTrigger';
        ts.TriggerOff__c= TRUE; 
        insert ts;
        Account a = new Account(Name='my account');
        insert a;
        Contact c = new Contact(FirstName='test',LastName='contact',AccountId=a.Id, Email='test@testdlkfjsdlkfj.com', Phone='8189432003', Abbreviated_Channel__c='Inbound ', lifecycle__c='Marketing Qualified', Created_via_Conversion_Process__c=False,Datetime_of_Partnership_Application__c=Date.today(), DateTime_Marketing_Qualified_Most_Recent__c=Date.today());
        insert c;
        
        Test.startTest();
        c.lifecycle__c = 'Sales Accepted';
        update c;
        Test.stopTest();
        List<Lifecycle_History__c> lifecyclelist1 = [SELECT Id, Contact__c FROM Lifecycle_History__c];
        List<Contact> contactlist1 = [SELECT Id, lifecycle__c FROM Contact];
        System.debug(c.lifecycle__c);
        System.debug(c.Id);            
        System.debug(JSON.serializePretty(lifecyclelist1));
        System.debug(JSON.serializePretty(contactlist1));
        c.lifecycle__c = 'Known';
        update c;
        System.debug(c.lifecycle__c);
        

            
        List<Lifecycle_History__c> lifecyclelist = [SELECT Id FROM Lifecycle_History__c WHERE Contact__c = :c.Id]; 
        System.assertEquals(3,lifecyclelist.size());
    } 
}