I'm trying to test for a trigger that insert a calculated duration of Event after insert/update of A Event record. For example, the trigger fills an integer representing hours, calculated from StartDateTime and EndDateTime of the subject Event record, to DurationInHours__c field.
The problem is that DurationInHours__c is null when System.assertEquals is executed. Error message says 'System.AssertException: Assertion Failed: Expected: 1, Actual: null'. Note that event duration is set to be 1 hour.
Please help me out.
Test code:
@isTest
public class TestUpdateDuration {
@isTest static void TestUpdateDuration() {
// Test data setup
// Create an event with 1 hour duration
User myUser =[select id from User where Email = '[email protected]'];
Datetime myStart = Datetime.newInstance(2019, 9,17, 7,0,0);
Datetime myEnd = Datetime.newInstance(2019, 9,17, 8,0,0);
Event ev = new Event(
StartDateTime = myStart,
EndDateTime = myEnd
);
insert ev;
// Verify
// In this case '1' should be added to DurationInHours__c field by the trigger,
// so verify if it is correct
System.assertEquals(1, ev.DurationInHours__c);
}
}
Trigger: Event record will have an event duration value in DurationInHours__c after update/insert. I manually check that a value is inserted and it was ok.
trigger updateDuration on Event (after update, after insert) {
List<Event> listEvents = new List<Event>();
for ( Event e : Trigger.new ) {
Event updateE = [select id, EndDateTime, StartDateTime, DurationInHours__c, DurationInMinutes, IsAllDayEvent from Event where id = :e.id];
// How many days will that event last?
Long msecStart = updateE.StartDateTime.getTime();
Long msecEnd = updateE.EndDateTime.getTime();
Long msecDuration = msecEnd - msecStart;
Long elapsedHours = 0;
if(updateE.IsAllDayEvent) {
elapsedHours = 8;
} else {
elapsedHours = ((msecDuration / 1000) / 60) / 60;
}
if(updateE.DurationInHours__c != elapsedHours) {
updateE.DurationInHours__c = elapsedHours;
listEvents.add(updateE);
}
}
update listEvents;
}