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
RstrunkRstrunk 

Yet another Apex Test Class Post

Hi all, 

   From time to time I see people post their triggers and test classes in order to figure out why it isn't behaving as expected.  Looks like it's my turn :-)

 

Here is my trigger:

trigger UpdateLastVisitDate on Task (before insert) {
    system.debug('######################  ENTERING TASK TRIGGER  ################################');
    list<id> eventRelatedIds = new list<id>();
    list<account> relAccounts = new list<account>();
    list<contact> relContacts = new list<contact>();
    date n = date.today();
    
    system.debug('######################  TRIGGER.NEW :'+TRIGGER.NEW+'  ################################');
    
    for(integer i =0; i < trigger.new.size(); i++){
        SYSTEM.DEBUG('TRIGGER.NEW.TYPE : ' + TRIGGER.NEW[I].TYPE);
        if(trigger.new[i].type == 'Visit-BD'){
            SYSTEM.DEBUG('TRIGGER.NEW.WHOID : ' + TRIGGER.NEW[I].WHOID);
            if(trigger.new[i].whoId != null){
                eventRelatedIds.add(trigger.new[i].whoId);
            }
            SYSTEM.DEBUG('TRIGGER.NEW.WHATID : ' + TRIGGER.NEW[I].WHATID);
            if(trigger.new[i].whatId != null){
                eventRelatedIds.add(trigger.new[i].whatId);
            }
        }
    }
    
    SYSTEM.DEBUG('eventRelatedIds : ' + eventRelatedIds);
    if(eventRelatedIds != null && eventRelatedIds.size() > 0){
        relAccounts = [select id, Last_Visit__c from Account where id IN:eventRelatedIds];
        relContacts = [select id, Last_Visit__c from Contact where id IN:eventRelatedIds];
    }
    
    SYSTEM.DEBUG('relAccounts : ' + relAccounts);
    if(relAccounts != null && relAccounts.size() > 0){
        for(integer i = 0; i < relAccounts.size(); i++){
            relAccounts[i].last_visit__c = n;
            SYSTEM.DEBUG('relAccounts[i].last_visit__c : ' + relAccounts[i].last_visit__c);
        }
        update relAccounts;
    }
    
    SYSTEM.DEBUG('relContacts : ' + relContacts);
    if(relContacts != null && relContacts.size() > 0){
        for(integer i = 0; i < relContacts.size(); i++){
            relContacts[i].Last_Visit__c = n;
            SYSTEM.DEBUG('relContacts[i].Last_Visit__c : ' + relContacts[i].Last_Visit__c);
        }
        update relContacts;
    }
    system.debug('######################  LEAVING TASK TRIGGER  ################################');
}

 

And here is my TestClass:

@istest(SeeAllData=true)
private class TestLastVisitUpdate{
    static testmethod void createTasks(){
        integer createTask = 0;
        Account tmpAccount = new Account(Name = 'Test Account', last_Visit__c = null);
        if(tmpAccount != null){insert tmpAccount; createTask += 1;}
        Contact tmpContact = new Contact(LastName = 'Test Name', Account = tmpAccount, Speciality__c = 'N/A', last_Visit__c = null);
        if(tmpContact != null){insert tmpContact; createTask += 1;}
        
        if(createTask == 2){
            List<Task> tasks = new List<Task>();
            tasks.add(new Task(
                ActivityDate = Date.today().addDays(7),
                Subject = 'Sample Task',
                WhatId = tmpAccount.id,
                type = 'Visit-BD',
                OwnerId = UserInfo.getUserId(),
                Status='In Progress'));
                
            tasks.add(new Task(
                ActivityDate = Date.today().addDays(7),
                Subject = 'Sample Task',
                WhoId = tmpContact.Id,
                type = 'Visit-BD',
                OwnerId = UserInfo.getUserId(),
                Status='In Progress'));
            if(tasks.size() > 0 && tasks != null){
                test.starttest();
                insert tasks;
                system.debug('############### ACCOUNT INFO:' + tmpAccount + '####################');
                system.debug('############### CONTACT INFO:' + tmpContact + '####################');
                system.assertnotequals(tmpAccount.last_visit__c , null);
                system.assertnotequals(tmpContact.last_visit__c , null);
                test.stopTest();
            } 
            system.debug('############### TASK INFO:' + tasks + '####################');
        }   
        createTask = 0;
    }
}

 

I don't understand why the assertion fails.  The debug statement shows the value of the last_visit__c field is populated while inside the trigger, but when it comes back to the class the field is somehow null if that makes sense.  

 

I'm sure it is a very basic mistake I made.  Any help would be appreciated!!!

 

Thanks, 

Best Answer chosen by Admin (Salesforce Developers) 
sfdcfoxsfdcfox

The variables tmpAccount and tmpContact are copies of data at the time it was created or retrieved from the database. They are not live links to the actual data-- when the database is updated, those variables still hold the original information. The solution, then, is that you must re-query tmpAccount and tmpContact from the database after the trigger completes. A simple version would look like:

 

insert tasks;
tmpAccount = [select id, last_visit__c from account where id = :tmpAccount.Id];
tmpContact = [select id, last_visit__c from contact where id = :tmpContact.Id];
system.assertnotequals(...

 

All Answers

sfdcfoxsfdcfox

The variables tmpAccount and tmpContact are copies of data at the time it was created or retrieved from the database. They are not live links to the actual data-- when the database is updated, those variables still hold the original information. The solution, then, is that you must re-query tmpAccount and tmpContact from the database after the trigger completes. A simple version would look like:

 

insert tasks;
tmpAccount = [select id, last_visit__c from account where id = :tmpAccount.Id];
tmpContact = [select id, last_visit__c from contact where id = :tmpContact.Id];
system.assertnotequals(...

 

This was selected as the best answer
RstrunkRstrunk
Thanks! Very helpful as usual!! People like you are at the core of what makes Salesforce prosper.