Set created date in test records in the test class

by Rijwan Mohmmed
0 comment
How-to-set-created-date-in-test-records-in-the-test-class

Hello, friends today we will learn Set created date in test records in the test class, Sometimes the requirement is to set the created date to a specific past date on the records. So to achieve this we can use Test.setCreatedDate(Id recordId, Datetime created date) function. This function accepts two parameters. One is recordId and another is the createdDatetime. So recordId is the id of the record whose created date we are trying to set and the created date is the value we want to set.

If you set CreatedDate to a future value, it can cause unexpected results.

@isTest 
private class TestCreatedDate {
    static testMethod void testSetCreatedDateOnAccount() {
        Account acc = new Account(name='myAccount');
        insert acc;
        DateTime createdDate = DateTime.newInstance(2010,1,10); 
        Test.setCreatedDate(acc.Id, createdDate);
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, createdDate);
        Test.stopTest();
    }
}
What’s your Reaction?
+1
0
+1
0
+1
0
+1
0
+1
0
+1
0

You may also like

Leave a Comment

* By using this form you agree with the storage and handling of your data by this website.