Modifying System Fields (LastModifiedDate and CreatedDate) for Test classes in Salesforce Apex
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 :
TIPS —
- You can use Test.setCreatedDate while working while created date field.
- You can use JSON.Deserialize for created date field as well. But both methods do not work for LastModifiedDate.
How Can You Contribute?
- Connect with me on Linkedin/Twitter
- Endorse me on Linkedin for Salesforce
- Reach me out on LinkedIn, if my knowledge in salesforce can help you.
Posts in the previous series :
Salesforce Development — Learning Apex Programming, VisualForce, Lightning Components
First Step toward Learning Apex Programming
Day 2 in Apex — Writing apex codes
Working with sObjects, SOQL, and SOSL
Understanding Salesforce Triggers and working with them
Apex Test classes and methods
Understanding VisualForce Concepts
Controllers in VisualForce