Set Record Created Date In Test

How to set record created date in Apex Unit Test?

You can use Test.setCreatedDate to set the CreatedDate of the inserted record inside Unit Test. This is helpful when the logic you’re testing depends on the records’ creation date - for…

You can use Test.setCreatedDate to set the CreatedDate of the inserted record inside Unit Test. This is helpful when the logic you’re testing depends on the records’ creation date - for example, a batch job that clears all Log__c records older than 5 days.

apex
@IsTest
static void yourBatchTestExample() {
    Log__c log = new Log__c(
        Body__c = 'Sample log body',
        Category__c = LogCategory.INFO
    );
    insert log;

    Test.setCreatedDate(log.Id, DateTime.now().addDays(-10));

    Test.startTest();
    Database.executeBatch(new LogsClearBatch());
    Test.stopTest();

    Integer logsNumber = [SELECT COUNT() FROM Log__c];
    Assert.areEqual(0, logsNumber, 'Log created 10 days ago should be deleted.');
}

Let’s check an example

Text and code were extracted from the original slide. Plain-text version of the whole catalog