You are using an older browser that might negatively affect how this site is displayed. Please update to a modern browser to have a better experience. Sorry for the inconvenience!

Dynamic Created Date and Modified Date in Apex Test Class

By: Venkata

Apex Test Class :

Recently we came across an issue that we want to share with you all and explain the solution. Normally, in Salesforce Test classes, we create test records to test the functionalities of the code, but the problem is whenever we insert the test records in test class, we can’t specify the CreatedDate since it is a Read Only Field.

In our scenario, we will be creating Tasks for the same business when Leads are created during the business hours (9 AM to 5 PM -May vary among organizations). If the Lead is created outside of business hours, the task will be created in the next business day.

So the code tries to access the CreatedDate (time) and creates tasks accordingly. Whenever, we create the test records in the test class, the whole code can’t be covered because the code coverage is based on the time that we run the test class. In other words, the code coverage will work either for business hours or non-business hours at a time.

However, inserting test records within or out of business hours is not possible until we are able to make the CreatedDate field as dynamic. So, in order to get 100% code coverage, we inserted test records that would have date and time within the business hours as well as out of business hours. Therefore, the solution is to make the CreatedDate field dynamic for test class.

We prepared the test records in a csv file with CreatedDate column and uploaded it as static resource, referred the static resource file in the test class, and loaded the test records using Test.loadData method.

Here is the code:

1.	@istest
2.	public class TestLeadTaskAutoCreation{
4.	  public static testMethod void test()
5.	{
6.	// TestLeadCreatedDate is the name of static resource which contains a CSV file with Test Lead records that will be inserted during the test run.
7.	// We can make use of Test.loadData method instead of inserting test record in the test class - that can reduce the no of lines of code in the test class.
8.	// Date Field will not be Read only field when we use Test.loadData method.
9.	        final String staticResourceName = 'TestLeadCreatedDate';
10.	        final Lead[] testAccounts = (Lead[]) Test.loadData(Lead.sObjectType, staticResourceName);
11.	 }
13.	}

Data file:
Static Resource File – TestLeadCreatedDate.csv

Reference Links:
Loading Salesforce Apex Test Data
Loading Salesforce Test Data from Static Resources