+ Start a Discussion
KatherineCKatherineC 

How To Insert Date/Time In Test Class

Hi All,
I created a trigger, so that when a new event is created in Public Calendar a new CalendarEV record will be created automatically. I got error message after running test class that missing required fields, so no code coverage at all. I noticed that both Start and End fields in Event object are required Date/Time fields, so I wonder how to create Date/Time in test class for these two fields so that an event can be created and fire the trigger. Please help.

Error message: System.DmLException: insert failed. First exception on row 0; First error, Required field missing
Stack Trace: Class.CalendarEVTest.insertNewCalendarEV: Line11, colum 1

trigger CalendarEV on Event (after insert) {
List<Event> Events = new List<Event>();
   for (Event e : Trigger.new) {
           if (e.Subject != null ) {
               CalendarEV__c C = new CalendarEV__c();
               c.Name = e.Subject;
               c.Start__c = e.StartDateTime;
               c.End__c = e.EndDateTime;
               c.Location__c = e.Location;
               c.Description__c = e.Description;
                    
              insert C;
        }
    }
   }


@isTest
public class CalendarEVTest
{
    static testMethod void insertNewCalendarEV()
    {
        Test.StartTest();
        Event e = new Event();
        e.Subject = 'Test Event';
        e.Location = 'Test Location';
        e.Description = 'Test Description'; 
        insert e;
        Test.StopTest();
        System.assertEquals ('Test Event', e.Subject);
    }
}
Best Answer chosen by KatherineC
sbbsbb
You can do something like this:

e.StartDateTime = datetime.newInstance(2014, 9, 15, 12, 30, 0);
e.EndDateTime = datetime.newInstance(2014, 9, 15, 13, 30, 0);

Here is the signature for the newInstance method:

public static Datetime newInstance(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second)


All Answers

sbbsbb
You can do something like this:

e.StartDateTime = datetime.newInstance(2014, 9, 15, 12, 30, 0);
e.EndDateTime = datetime.newInstance(2014, 9, 15, 13, 30, 0);

Here is the signature for the newInstance method:

public static Datetime newInstance(Integer year, Integer month, Integer day, Integer hour, Integer minute, Integer second)


This was selected as the best answer
KatherineCKatherineC
Yay, it works!! Thanks so much sbb!! We're good to go!