Manipulate CreatedDate property of test-context sObjects

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 =;
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!

Author: Matt

Matthew is a highly accomplished and award-winning programmer who is well versed in a variety of the hottest technologies powering today's most successful companies. With 11+ years of experience, Matthew has done it all: from the most rudimentary tasks to complex implementations of entire applications, CRMs, and pieces thereof. Today he spends his time mastering administration, development, and implementation as he mediates between stakeholders and project owners to successfully interface a complex company in a complex industry.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.