Manipulate CreatedDate property of test-context sObjects

Matt/ July 5, 2016/ Salesforce, Technology

One thing I somehow missed in the Spring ’16 update is a new method in the System.Test class called setCreatedDate() .


Why is this important?

Suppose you were trying to test an update trigger on an sObject, and you wanted to look at the timespan between created date and now. What you need to do is create a record with CreatedDate in the past. The problem is CreatedDate is an audit field, and can’t be written to.

This method is easy to use and does as advertised: sets CreatedDate for a test-context sObject.

Account account = new Account(Name = 'My Test Account');
insert account;

Datetime yesterday = Datetime.now().addDays(-1);
Test.setCreatedDate(account.Id, yesterday);

And now you can go about writing the rest of your test class.  If you missed this little notice as well, I hope I’ve made your life easier!

Share this Post

About Matt

Matt McGuire is a Salesforce architect, AI builder, and punk musician based in Toronto. Canada's #1 certified Salesforce professional, 42× certified across architecture, development, AI, and a wide range of platform products. He's been building on Salesforce for 17 years and currently spends most of his time at the intersection of AI and the platform. The Music Intelligence Engine is his most interesting project to date. He thinks you should read the whole series.