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
JJE_OLDJJE_OLD 

Before Insert, Before Update trigger, Test Class failed

Hi,

 

I created a Trigger on Opportunity, which updates a custom date field.

 

trigger SetOpportunityEndDate on Opportunity (before insert, before update) {

for (Opportunity op: Trigger.new) {

...

        op.MaintenanceEndDate__c = op.Maintenance_Start_Date__c.addMonths(op.Maintenance_Duration__c.intValue());

...

        system.debug('*****************************' + op.MaintenanceEndDate__c);    
    }

}

 

My Test class is like the following:

 

@isTest
private with sharing class testEndDate {
    public static testMethod void testOpportunityEndDate() {
        Opportunity op = new Opportunity();
        //Fields Initialization

        op.Maintenance_Duration__c = 2;


        Insert op;

        system.debug('******************************************************End Date: ' + op.MaintenanceEndDate__c);
        system.assertEquals(op.Maintenance_Start_Date__c.addMonth(2), op.MaintenanceEndDate__c);      
    }
}

 

When I run my tests, the trigger System.debug gives me the correct end date.

But after insert op in the test class the End date is null in the system.debug and the following assertEquals fails.

 

When I made a change on an Opportunity in my sandbox, the end date is correctly calculated. Does it have something to do with the Insert?

 

What am I doing wrong?

 

thanks,

Best Answer chosen by Admin (Salesforce Developers) 
Cory CowgillCory Cowgill

You need to query for the updated result and assert against that.

 

When you perform an insert DML statement in your test class, the only field that gets updated is the ID. The other fields that are modified during the trigger don't get updated. You need to Query for the result.

 

@isTest
private with sharing class testEndDate {
    public static testMethod void testOpportunityEndDate() {
        Opportunity op = new Opportunity();
        //Fields Initialization

        op.Maintenance_Duration__c = 2;


        Insert op;
        Opportuinty resultOppty = [Select Id, Name,Maintenance_Start_Date__c,MaintenanceEndDate__c from Opportunity where Id = :op.Id ];
        system.debug('******************************************************End Date: ' + op.MaintenanceEndDate__c);
        system.assertEquals(resultOppty.Maintenance_Start_Date__c.addMonth(2), resultOppty.MaintenanceEndDate__c);    
  
    }
}