Spring '16 Release Notes document a new system method supporting this:
Test.setCreatedDate(recordId, createdDatetime)
Sets CreatedDate for a test-context sObject.
This will definitely complement the loadData()
and deserialize()
techniques.
Account account = new Account(Name = 'Test');
insert account;
Datetime yesterday = Datetime.now().addDays(-1);
Test.setCreatedDate(account.Id, yesterday);
Test Class: Contains methods related to Apex tests.
setCreatedDate(recordId, createdDatetime)
Sets CreatedDate for a test-context sObject.
All database changes are rolled back at the end of a test. You can’t use this method on records that existed before your test was executed. You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true)
, because those methods have access to all data in your org. If you set CreatedDate to a future value, it can cause unexpected results. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
Insert your test record before you set its CreatedDate, as shown in this example.
@isTest
private class SetCreatedDateTest {
static testMethod void testSetCreatedDate() {
Account a = new Account(name='myAccount');
insert a;
Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));
Test.startTest();
Account myAccount = [SELECT Id, Name, CreatedDate FROM Account
WHERE Name ='myAccount' limit 1];
System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2012,12,12));
Test.stopTest();
}
}