Tag Archives: Set CreatedDate

Set CreatedDate Field Value for Test Class Records in Salesforce

As of Spring ’16 release, we can now set the Created date field value for the test records in Salesforce test classes using setCreatedDate(Id recordId, Datetime createdDatetime) method.

Example:

@isTest   
private class SampleTest {  
    static testMethod void testSetCreatedDate() {  
        Account acc = new Account(Name='Test Account');  
        Insert acc;
        Datetime yesterday = Datetime.now().addDays(-1);
        Test.setCreatedDate(acc.Id, yesterday);  
        Test.startTest();  
        Account testAcc = [SELECT Id, Name, CreatedDate FROM Account WHERE Name ='Test Account' LIMIT 1];  
        System.assertEquals(testAcc.CreatedDate, yesterday);  
        Test.stopTest();  
    }  
}  

Note:

  • All database changes are rolled back at the end of a test. We can’t use this method on records that existed before the test executed.
  • We also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in the org.
  • The both parameters (Id recordId, Datetime createdDatetime) of this method are mandatory.