Modifying System Fields (LastModifiedDate and CreatedDate) for Test classes in Salesforce Apex

Prakher Chaturvedi
3 min readJul 17, 2021

--

We usually come across scenario where we are stuck and don’t know our way forward. It is a usual affair while continuously working within different phases (Solution designing, writing apex classes and test classes) of Salesforce Development. Writing Apex Test class is an important phase and following best practices blocks you from using your Salesforce org’s data.

So as most of my previous blogs/stories targeted people willing to dive in Salesforce environment. Here comes a scenario where one can get stuck if he wants to write a test class for an apex class which processes records queried on system protected field such as CreatedDate, LastModifiedDate. If you have the same case, you can reach out to this blog as here I have explained the scenario and also it’s implementation.

Scenario — -We wrote an apex class where it works on records returned from specific SOQL query having a WHERE clause on System modified fields such as Created Date, Last modified Date and others.
In the above scenario, while creating records in test class to satisfy the specific SOQL we may face issue in updating system modified date fields. Below is the solution how to.

Solution — While looking for the solution of above query I came across this useful knowledge article in salesforce and you can go through this one as well.

The solution which worked as expected was Using Test.loadData()

I tried both the solutions from the above linked article and JSON.deserialize() didn’t work as expected for me when working with lastModifiedDate. As querying the record once it was inserted returned last modified date as current dateTime. It works as expected for created Date.

Let’s Talk about the solution which worked.

Pre-Requisites : You need to update the records you want your test class to process, in a csv file and upload it as a static resource in your salesforce org.

Syntax : Test.loadData(ObjectName.sObjectType, ‘Static_Resource_Name’);

Implementation :

This method updates site of Accounts which are modified before Yesterday and site is null
This Test Class loads records from static resource and performs execution on them
Run Test class with System.debug to affirm lastModifiedDate is not changed
Debug Logs Stating LastModifiedDate is not changed

TIPS

  1. You can use Test.setCreatedDate while working while created date field.
  2. You can use JSON.Deserialize for created date field as well. But both methods do not work for LastModifiedDate.

--

--

Prakher Chaturvedi

Looking for remote opportunities | Salesforce Developer | Lightning Web Components | APEX | 5x Certified | Trailhead Ranger | Content Creator (Medium)