How to set CreatedDate for records in Test Class in Salesforce?

How to set CreatedDate for records in Test Class in Salesforce?

💡 Mastering Test.setCreatedDate(): How to Set Record CreatedDate in Salesforce Test Classes?


Why Control CreatedDate in Your Salesforce Tests? 📅

As a Salesforce developer, you often encounter Apex code, like Triggers, Batch Apex, or utility classes, that relies on system fields such as CreatedDate or LastModifiedDate.

For example, you might have a Batch Apex class that archives records older than 30 days, or a Trigger that performs logic based on a record’s age. To properly test these scenarios, your unit tests must be able to create data with a specific, past CreatedDate—something you can’t do with a standard DML operation since CreatedDate is a read-only system field.

Fortunately, Salesforce provides a powerful, specialized method for this exact purpose: Test.setCreatedDate().


How to Use Test.setCreatedDate()

The Test.setCreatedDate() method is a static method in the System.Test class that allows you to override the CreatedDate system field for an sObject record within a test class.

The Key Method Signature

Sample Apex

Test.setCreatedDate(recordId, createdDatetime);
  • recordId: The ID of the sObject record whose CreatedDate you want to set.
  • createdDatetime: The Datetime value you want to assign to the record’s CreatedDate field.

Sample Code Implementation

To successfully use this method, you must insert the record first to generate an ID, and then call Test.setCreatedDate() using that ID.

Here is a sample implementation using the Account object:

Sample Apex Code:

Account a = new Account(name='myAccount');
insert a;
Test.setCreatedDate(a.Id, DateTime.newInstance(2012,12,12));

After this code executes, the Account record with the ID stored in a.Id will have a CreatedDate value of December 12, 2012. You can then query this record in your test to verify your business logic works correctly.


Important Best Practices and Notes 📌

When using Test.setCreatedDate(), there are a few critical instructions and best practices to follow to ensure your tests run correctly and reliably:

  1. Do Not Use seeAllData=true:The Test.setCreatedDate() method is designed to work with test data created within the test context. It is explicitly disallowed in any test method annotated with @isTest(SeeAllData=true) because those methods access production data, and manipulating audit fields on production data is not permitted. Always stick to creating your own test data.
  2. Timing is Crucial: Call Before Test.startTest():The Test.setCreatedDate() method should be called before the Test.startTest() method. The general pattern for a unit test is:
    • Set up Test Data (including calling Test.setCreatedDate() to manipulate dates).
    • Call Test.startTest() (to reset governor limits and begin the code to be tested).
    • Execute the code being tested (e.g., DML, method calls).
    • Call Test.stopTest() (to wait for asynchronous processes).
    • Assertions (to verify results).
  3. Use It for Single Records (Iterate for Bulk):The standard Test.setCreatedDate() method is designed to take a single record ID. If you need to set the CreatedDate for multiple records (which is a best practice for testing bulkification), you must insert all your records and then iterate over the list of records to call Test.setCreatedDate() for each one individually.

This powerful method is essential for writing complete and robust unit tests, especially for time-based business logic in Salesforce.

Leave a Reply