I have a class that processes some data returned by a query. The query is based on the createddate column of the object. In this case, the query specifically retrieves data created 3 days before today.

So as an example, the query would have the

Select Id, Name, Amount__c FROM MyCustomObject__C WHERE CreatedDate = TODAY - 3 as the condition to fetch records.

In my test class any records I insert in the MyCustomeOBject__c would always have the CreatedDate = TODAY

So how can I make test data that was created 3 days ago?


2 Answers 2


You can use following:

Test.setCreatedDate(recordId, createdDatetime);

Sets CreatedDate for a test-context sObject.

Datetime testingday = Datetime.now().addDays(-3);
Test.setCreatedDate(MyCustomObject__c.Id, testingday); 
  • Good answer. I am stuck in another part of my test class. I believe this will solve the issue. Thx.
    – abhi
    Jul 7, 2016 at 18:57

You can use the below method

 Account a = new Account(name='myAccount');

 insert a;

 Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
  • 1
    What I am suggesting here is that sometimes we have to process very old historical data example previous year 21 Jan data, so giving Dateime.now().addDays(-3) would become difficult to count days, so giving DateTime.newInstance(2012,12,12) is an easier alternative. May 6, 2022 at 8:55

You must log in to answer this question.

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