-2

Please help me to write test class for event object. I am getting only 25% code coverage.

// Method to validate start and End Time on events
    public static void ValidateStartEndTime(List<Event> evts) {
        for(Event ev: evts)
        {
            if(ev.StartDateTime.time() < Time.newInstance(7, 30, 0, 0))
            {
                ev.StartDateTime.addError('Start time should be greater than or equals to 7:30 AM');
            }
            if(ev.EndDateTime.time() > Time.newInstance(18, 00, 0, 0))
            {
                ev.EndDateTime.addError('End time should be less than or equals to 6 PM');
            }
        }
    }

Test class:

@isTest
public class EventTrigger_Test {

    static testMethod void myUnitTest1(){

        Event e = new Event();
        e.StartDateTime=system.today();
        e.EndDateTime=system.today()+5;

        Test.startTest();  
            insert e;
        Test.stopTest();
    }
}
0

1 Answer 1

1

In the test method you have two problems:

1- The AddError will stop from going forward in the code, so if you get into the first if-statement you won't get into the second. That's why you need two seprate test methods.

2- The logic in the trigger check only the time and not the date, so it doesn't matter in which day you are, as long the time is good (between 7:30 and 6). That means you will have to change the time in the test method.

You can check this LINK to see how to set the datetime (also the time)

5
  • Can you show me syntax to cover date time with sample test class.
    – Sohel
    Aug 1, 2019 at 11:29
  • 1
    e.StartDateTime = Datetime.newInstance(2019, 1, 1, 03, 00, 00); --> This is (03:00 am)
    – Mo Hamada
    Aug 1, 2019 at 11:31
  • It's not covering.Can you please write the test code syntax for class
    – Sohel
    Aug 1, 2019 at 12:09
  • 1
    try to print out some System.debug to check the values in every stage and why it's not getting in the if-statements
    – Mo Hamada
    Aug 1, 2019 at 12:10
  • @Sohel for e.StartDateTime and e.StopDateTime please enter a new instance of time as Mo Hamanda showed. Otherwise the test will sometimes pass and sometimes fail depending on the time of day it is.
    – bemon
    Aug 1, 2019 at 13:28

Not the answer you're looking for? Browse other questions tagged .