I created a schedule class to run an update for all leads created 5 days ago On the test class, I do create a lead BUT I can't set the scheduler to run 5 days AFTER the lead was created (Today + 5 days)

How should I fix it?

enter image description here

  • 1
    How much %age covered? Can you share your schedule class as well?
    – Mahmood
    Dec 15, 2014 at 13:56

2 Answers 2


Luckily Salesforce does provide us with an option for your scenario. You can use the Test.LoadData(..) method to insert test data with old created date values. The article below has all the details. Setting system protected fields for test code coverage


In testmethods, it doesn't matter what the schedule time is, the scheduler executes as soon as the Test.stopTest() statement is encountered.

The System.schedule method starts an asynchronous process. This means that when you test scheduled Apex, you must ensure that the scheduled job is finished before testing against the results. Use the Test methods startTest and stopTest around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don’t include the System.schedule method within the startTest and stopTest methods, the scheduled job executes at the end of your test method for Apex saved using Salesforce API version 25.0 and later, but not in earlier versions.

So, you need to do your asserts on Lead after the Test.stopTest() statement.

Now, if you need to insert Lead test data with a createdDate in the past, you can do as @AAU suggested or, to avoid having to manage another resource in your system (that is, the StaticResource), you can create the Lead simply inline as follows:

String fiveDaysAgo = System.now().addDays(-5).format('YYYY-MM-dd');
Lead l = (Lead) Json.deserialize('{"company":"foo", "lastname":"bar",' +
                                   '"email":"[email protected]", "createddate":' +
                                    '"' + fiveDaysAgo + '"}',
insert l;
system.debug(LoggingLevel.INFO,'lead (proof) =' +
       [select id, createdDate from lead where id = :l.id]);

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .