[SalesForce] Unit testing code which has logic around the CreatedDate

An example of the problem would be trying to test a trigger on a case which will fire on update, and look for time differences between when a case was created and now. Ideally in the unit tests I want to create a case with a CreatedDate in the past. The problem here is that CreatedDate is an audit field and not writeable[1]. Is there a standard work around to this problem?

[1] I know you can get audit fields turned on to be writeable temporarily when doing data migration. This is not a viable solution for every time you want to get your code coverage up for deployment.

Best Answer

Spring '16 Release Notes document a new system method supporting this:

Test.setCreatedDate(recordId, createdDatetime)

Sets CreatedDate for a test-context sObject.

This will definitely complement the loadData() and deserialize() techniques.

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

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