Wednesday, October 28, 2020

How to set CreatedDate field value for Test Class Records in Salesforce

We can now set the Created date field value for the test records in Salesforce test classes using setCreatedDate(Id recordId, Datetime createdDatetime) method. 

Note: Both recordId and DateTime parameters are required.

Example:

@isTest 
private class SetCreatedDateTest {
    static testMethod void testSetCreatedDate() {
        Account a = new Account(name='myAccount');
        insert a;
        Test.setCreatedDate(a.Id, DateTime.newInstance(2020,12,12));
        Test.startTest();
        Account myAccount = [SELECT Id, Name, CreatedDate FROM Account 
                             WHERE Name ='myAccount' limit 1];
        System.assertEquals(myAccount.CreatedDate, DateTime.newInstance(2020,12,12));
        Test.stopTest();
    }
}


No comments:

Post a Comment