[SalesForce] How to create test objects with lastModifiedDate in past

So I created a Job that is supposed to run every day and give me a list of Opportunity records that have not been modified in the last 6 months, so I can email the owner and let him/her know that the status of that record will change to Closed Lost. When I'm writing the test class for this I'm running into an issue. I can not set the LastModifiedDate to 180 days ago. I've read and I was told that I can use Dependency Injection to put any date I want but I don't know how to do that, has anyone done it before? Do you have a sample code I could use?
Thanks in advanced.

Best Answer

One way to create testdata with lastModifiedDate in the past is through Test.loadData()

Step 1- Create CSV File for your sobject

name    createdDate            lastmodifiedDate
00foo   2000-01-01T00:00:00Z    2001-01-01T00:00:00Z
01foo   2000-01-02T00:00:00Z    2001-01-02T00:00:00Z

Step 2 - save as Static Resource (named here as sfseLastModDateInPast)

Step 3 - Code test method

@istest
private static void testLastModDateInPast () {

    Foo__c[] fList = test.loadData(Foo__c.sObjectType,'sfseLastModDateInPast');
    system.debug(loggingLevel.INFO,fList);
}

Notes

If your object has triggers then you'll want to disable before executing Test.loadData as otherwise the triggers may cause lastModifiedDate to be refreshed to now

If you need to create relationships in the static resource, use external IDs or see undocumented tip here

Debug output (truncated)

  10:34:13:261 USER_DEBUG [7]|INFO|(Foo__c:{
     Id=a1pJ0000003ocTAIAY, 
     Name=00foo, 
     CreatedDate=2000-01-01 00:00:00,  // in past
     LastModifiedDate=2001-01-01 00:00:00, // in past
     SystemModstamp=2016-01-02 18:34:09, ... )
Related Topic