Until Winter 16, You won't able to set created date for records which you are creating in Test class. By default, Created Date will be the current date while running test.
Beginning from Spring 16, You can set your own custom date as Created Date in test class.
Syntax:
- setCreatedDate(Id recordId, Datetime createdDatetime);
Sample Code:
- @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();
- }
- }
Note:
1. All database changes are rolled back at the end of a test.
2. You can’t use this method on records that existed before your test executed.
3. You also can’t use setCreatedDate in methods annotated with @isTest(SeeAllData=true), because those methods have access to all data in your org.
4. This method takes two parameters—an sObject ID and a Datetime value—neither of which can be null.
Reference: