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.
2 Answers
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, ... )
I would just manipulate your QueryLocator
.
public class MyBatch implements Database.Batchable<SObject>
{
@TestVisible static String whereClause = 'WHERE LastModifiedDate < LAST_N_MONTHS:6';
static final String soql = 'SELECT Id FROM Opportunity ' + whereClause;
// other logic
}
Then in your test just change the clause to an empty string or whatever you like.
Database.insert
you can insert audit fields as the doc states it applies only to the API - and the API is not available in testmethods. I'm not sure I understand your question -- to test a batchable class invoked byDatabase.execute()
that uses a start() queryLocator, you need to mock persistent data ..otherwise, you can test just the execute() method with sobjects created by JSON.deserialize (but this doesn;t test the start() method)