How to set CreatedDate field value In Test Class Salesforce

by Rijwan Mohmmed
0 comment

Many times we got problems setting a created dates in test class so today we will learn how to set this field value in any record in the test class.

We can set created date field value by this method setCreatedDate(Id recordId, Datetime createdDatetime) 

Here is an Example :

public class TechdicerTest {
    static testMethod void UnitTestMethod1() {
        Contact con = new Contact(lastname='testcontact');
        insert con; // insert a contact
        //set createddate field value
        Test.setCreatedDate(con.Id, DateTime.newInstance(2021,08,04));
        Contact ct = [SELECT Id, LastName, CreatedDate FROM Contact 
                             WHERE LastName ='testcontact' limit 1];
        System.assertEquals(ct.CreatedDate, DateTime.newInstance(2021,08,04));

You may also like

Leave a Comment