Sub topic 9
Testing scheduled jobs
This chapter assumes you can write Apex test classes, know what @IsTest does, and have read the earlier chapters on the Schedulable interface, cron expressions, and System.schedule. Scheduled jobs run without a user present, so a test is the only place you see them work before production.
What a test can and cannot prove
A test cannot wait for a cron expression to fire. Inside a test, a scheduled job does not run on its timetable. It runs only when the test calls Test.stopTest(). Two things follow from this:
- You can test that the job is scheduled correctly by checking its
CronTriggerrecord. - You can test what the job does by calling
executedirectly, or by lettingTest.stopTest()run it.
Keep these as separate tests. One checks the schedule, and the other checks the logic.
Testing that the job is scheduled
Schedule the job between Test.startTest() and Test.stopTest(). Use a cron expression with a fixed future date so the job never matches a real run time.
@IsTest
private class EscalateStaleCasesTest {
@IsTest
static void jobIsScheduled() {
String cronExp = '0 0 0 15 3 ? 2099';
Test.startTest();
Id jobId = System.schedule('Test escalate stale cases', cronExp, new EscalateStaleCases());
CronTrigger before = [SELECT CronExpression, TimesTriggered FROM CronTrigger WHERE Id = :jobId];
System.assertEquals(cronExp, before.CronExpression);
System.assertEquals(0, before.TimesTriggered);
Test.stopTest();
}
}The query runs before Test.stopTest(). At that point the job has been stored but has not fired, so TimesTriggered is 0. The year 2099 keeps the next fire time far away.
Testing what the job does
Test the business logic without involving the scheduler. Create the data, create an instance of the class, and call execute. The method takes a SchedulableContext, and tests commonly pass null when the code does not use it.
Note that CreatedDate is set by the system, so a test record cannot be inserted with an old date directly. The LAST_N_DAYS:7 filter in EscalateStaleCases would match nothing in a fresh test. You can set the date with Test.setCreatedDate, which takes a record ID and a Datetime.
@IsTest
private class EscalateStaleCasesLogicTest {
@IsTest
static void oldOpenCaseBecomesHigh() {
Case oldCase = new Case(Subject = 'Old', Status = 'New', Priority = 'Low');
Case newCase = new Case(Subject = 'New', Status = 'New', Priority = 'Low');
insert new List<Case>{ oldCase, newCase };
Test.setCreatedDate(oldCase.Id, Datetime.now().addDays(-10));
Test.startTest();
new EscalateStaleCases().execute(null);
Test.stopTest();
System.assertEquals('High', [SELECT Priority FROM Case WHERE Id = :oldCase.Id].Priority);
System.assertEquals('Low', [SELECT Priority FROM Case WHERE Id = :newCase.Id].Priority);
}
}The test checks both sides of the filter. A record that should change does, and a record that should not change is left alone.
Letting the job run through the scheduler
If you want to confirm the whole path, schedule the job and let Test.stopTest() run it. All work the scheduled job starts, including a batch it launches, finishes synchronously at that call. After it, you can assert on the results.
@IsTest
private class NightlyTaskCleanupTest {
@IsTest
static void scheduledJobStartsBatch() {
Task t = new Task(Subject = 'Old', Status = 'Completed');
insert t;
Test.setCreatedDate(t.Id, Datetime.now().addDays(-400));
Test.startTest();
System.schedule('Test cleanup', '0 0 0 15 3 ? 2099', new NightlyTaskCleanup());
Test.stopTest();
System.assertEquals(0, [SELECT COUNT() FROM Task WHERE Id = :t.Id]);
}
}Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion on results fails, with no error | Asserting before `Test.stopTest()`, so the job has not run | Move the assertions after `stopTest` |
| The job changes no records | Test data does not match the filter, often because of `CreatedDate` | Use `Test.setCreatedDate` |
| `TimesTriggered` is not 0 | Read after `Test.stopTest()` | Query before `stopTest` |
| Duplicate job name error | Scheduling the same name twice in one test | Use distinct names per call |
Exercise
A test schedules a job between startTest and stopTest, then asserts that a record was updated. The assertion sits before Test.stopTest(), and it fails. Why, and how do you fix it?
Show answer
The scheduled job runs only when Test.stopTest() is called, so the record has not been updated at the point of the assertion. Move the assertion after Test.stopTest().
Exercise
Why does a test for EscalateStaleCases need Test.setCreatedDate, and what two records should it create?
Show answer
CreatedDate is set by the system on insert, so a fresh record never matches the LASTNDAYS:7 filter. Test.setCreatedDate backdates one record. The test should create one backdated open case, which must be escalated, and one new case, which must keep its priority.