The Problem
I have a batch that is querying records that are created today, using the CreatedDate
field on the object. In the test class, creating all the test data in the test setup method, I was not getting any coverage. After investigation, I found out the CreatedDate
was null on the test data.
The Solution
This is the query in my batch class.
[SELECT Id, Name FROM Contact WHERE CreatedDate = :Date.today()]
To resolve the problem, I used the Test.setCreatedDate(recordId, createdDatetime)
method in my Apex test class. This function allows you to define a custom date and time for the CreatedDate
field of the sObject record in the test class.
However, it's essential to note that you can't use setCreatedDate
in methods annotated with @isTest(SeeAllData=true)
. These methods have access to all data in your org, and manipulating CreatedDate
in such contexts can lead to unexpected results. Additionally, both the sObject ID and Datetime value passed to setCreatedDate
must not be null.
Here's a snippet demonstrating its usage:
Contact con = new Contact(
FirstName = 'Test',
LastName = 'Contact'
);
insert con;
Test.setCreatedDate(con.Id, Date.today());
Reference
For more information on Test.setCreatedDate
and other Apex testing methods, refer to the Salesforce developer documentation.