function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
DbjensenDbjensen 

How to set LastModifiedDate in test class

Hello - I need to set the LastModifiedDate in a test class to yesterday. The code below sets the created date to yesterday but the LastModifiedDate is still coming back as the current date/time. Any help would be appreciated. 

USER_DEBUG [452]|DEBUG|last modified date (Lead:{Id=00Q7j000002lrl2EAA, CreatedDate=2021-02-03 22:27:47, LastModifiedDate=2021-02-04 22:27:46}, Lead:{Id=00Q7j000002lrl3EAA, CreatedDate=2021-02-03 22:27:47, LastModifiedDate=2021-02-04 22:27:47})
 
        Datetime yesterday = Datetime.now().addDays(-1);
        Test.setCreatedDate(testLeadTwo.Id, yesterday);
        Test.setCreatedDate(testLeadOne.Id, yesterday);
        Test.startTest();
            Database.executeBatch(new SfToPcRetryUpdateRecords_BatchProcess());
        DateTime x5Min = System.now().addMinutes(-5);
            List<Lead> ldCreated = [SELECT ID, CreatedDate, lastmodifieddate FROM Lead WHERE 
                              lastmodifieddate >= LAST_N_DAYS:1 AND lastmodifieddate < :x5Min];
            System.debug('last modified date '+ldCreated);
        Test.stopTest();
 
AnudeepAnudeep (Salesforce Developers) 
I recommend checking this post

or you can follow the below steps

To create testdata with lastModifiedDate follow the below link

https://help.salesforce.com/articleView?id=000332070&type=1&mode=1

OR

Step 1- Create CSV File for your sobject
name createdDate lastmodifiedDate
Test1 2000-01-01T00:00:00Z 2001-01-01T00:00:00Z
Test2 2000-01-02T00:00:00Z 2001-01-02T00:00:00Z
Step 2 - save as Static Resource (named here as recordsWithLastModDateInPast)
Step 3 - Code test method
 
@istest
private static void testLastModDateInPast () {

    TestObj__c[] recordList = test.loadData(TestObj__c.sObjectType,'recordsWithLastModDateInPast');
    system.debug(loggingLevel.INFO,recordList);
}

 
DbjensenDbjensen
Hi Anudeep - Thanks for the response. Regarding using a CSV file and hardcoding a date. Will the test class fail when the current date exceeds 1 day? My query is looking for a lead created within the last 1 day and with a lastModifiedDate < Last 5 Min.  For example, if I hard code 2/4/2021 00:00:00Z, does the test class start failing on 2/6 since I don't have that date in the CSV file?