Sub topic 9
Testing Scheduled Jobs
This chapter assumes you can write Apex test classes with @IsTest, create test data, and use Assert or System.assertEquals. It also assumes you have read the earlier chapters on Schedulable, System.schedule, CronTrigger and Batch Apex. The examples reuse EscalateStaleCases, ArchiveOldTasksBatch and NightlyTaskCleanup from those chapters.
What a test must prove
A scheduled job can fail in three separate ways, and each needs its own test:
- The logic in
executeis wrong. It updates the wrong records, misses records, or breaks on bulk data. - The job is never registered. The cron expression is rejected, or the schedule is never created.
- A job that hands work to Batch Apex starts the batch incorrectly.
You cannot wait for a real clock in a test. Instead, the test framework lets you run the job on demand. Salesforce also requires 75% code coverage for deployment to production. Coverage only shows that lines ran, so assertions on the outcome matter more than the percentage.
How the test framework treats scheduled jobs
Asynchronous work started between Test.startTest() and Test.stopTest() is collected rather than queued. When Test.stopTest() runs, the framework executes that work synchronously, and your test continues afterwards. Scheduled jobs follow the same rule. If you call System.schedule inside the block, the job runs at Test.stopTest(), even when the cron expression points to a date far in the future.
Three consequences follow from this:
- Assertions about a job's effects go after
Test.stopTest(). - Assertions about the schedule itself, such as
TimesTriggeredbeing 0, go before it. - An unhandled exception inside the job surfaces at
Test.stopTest()and fails the test.
Test data
Test methods cannot see existing org data unless the class uses @IsTest(SeeAllData=true). Avoid that setting. Create the records the job should find, and the records it should leave alone.
The job from earlier chapters selects cases older than seven days, so the test needs records with an old CreatedDate. You cannot set CreatedDate in a normal insert. Insert the record first, then call Test.setCreatedDate:
@IsTest
private class EscalateStaleCasesBehaviorTest {
private static Case makeCase(String priority, String status, Integer ageInDays) {
Case c = new Case(Subject = 'Test case', Status = status, Priority = priority);
insert c;
Test.setCreatedDate(c.Id, Datetime.now().addDays(-ageInDays));
return c;
}
@IsTest
static void oldOpenCaseIsEscalatedWhenJobRuns() {
Case oldCase = makeCase('Low', 'New', 10);
Case newCase = makeCase('Low', 'New', 1);
Test.startTest();
System.schedule('Test escalate behavior', '0 0 0 15 3 ? 2099',
new EscalateStaleCases());
Test.stopTest();
Assert.areEqual('High',
[SELECT Priority FROM Case WHERE Id = :oldCase.Id].Priority,
'A case older than 7 days should be escalated');
Assert.areEqual('Low',
[SELECT Priority FROM Case WHERE Id = :newCase.Id].Priority,
'A recent case should be left alone');
}
}The test creates one record the job must change and one it must skip. A test that only checks the positive case would still pass if the WHERE clause were removed.
Calling execute directly
You do not have to go through the scheduler. execute is an ordinary method, so a test can call it. The job in this chapter ignores the SchedulableContext, so you can pass null:
@IsTest
static void executeCanBeCalledDirectly() {
Case oldCase = makeCase('Medium', 'New', 30);
Case closedCase = makeCase('Medium', 'Closed', 30);
Test.startTest();
new EscalateStaleCases().execute(null);
Test.stopTest();
Assert.areEqual('High',
[SELECT Priority FROM Case WHERE Id = :oldCase.Id].Priority);
Assert.areEqual('Medium',
[SELECT Priority FROM Case WHERE Id = :closedCase.Id].Priority,
'Closed cases must not be escalated');
}Add this method inside the EscalateStaleCasesBehaviorTest class from the previous example.
This version is easier to debug, because no scheduler is involved, and it adds a second negative case, a closed case. Direct calls do not exercise the cron registration, so you still need one test that uses System.schedule. If execute reads sc.getTriggerId(), pass a real context. You cannot construct a SchedulableContext yourself, so the usual approach is to move the logic into a separate method and call that from the test.
Verifying the schedule itself
System.schedule returns the ID of a CronTrigger. Querying it checks that the platform accepted your expression:
@IsTest
private class EscalateStaleCasesScheduleTest {
@IsTest
static void jobIsRegisteredWithExpectedTimetable() {
String cronExp = '0 0 0 15 3 ? 2099';
Test.startTest();
Id jobId = System.schedule('Test escalate schedule', cronExp,
new EscalateStaleCases());
CronTrigger before = [
SELECT CronExpression, TimesTriggered, NextFireTime, State
FROM CronTrigger
WHERE Id = :jobId
];
Assert.areEqual(cronExp, before.CronExpression);
Assert.areEqual(0, before.TimesTriggered,
'The job should not have fired before stopTest');
Assert.isNotNull(before.NextFireTime);
Assert.areEqual(2099, before.NextFireTime.year());
Test.stopTest();
}
}The year 2099 keeps the expression in the future whenever the test runs. Cron expressions evaluate in the scheduling user's time zone, while NextFireTime is stored in GMT. For that reason, the example checks only the year, which is the same in every time zone for 15 March.
If your code wraps System.schedule in a helper, for example a method that registers the job after deployment, test that helper. Call it, then query CronTrigger by job name and assert on the result. That catches typos in the stored cron string.
Testing a job that starts Batch Apex
For a scheduled class that calls Database.executeBatch, the test follows the same pattern. The batch also runs at Test.stopTest().
@IsTest
private class NightlyTaskCleanupTest {
@IsTest
static void oldClosedTasksAreDeleted() {
Task oldTask = new Task(Subject = 'Old', Status = 'Completed');
Task recentTask = new Task(Subject = 'Recent', Status = 'Completed');
insert new List<Task>{ oldTask, recentTask };
Test.setCreatedDate(oldTask.Id, Datetime.now().addDays(-400));
Test.startTest();
System.schedule('Test nightly task cleanup', '0 0 0 15 3 ? 2099',
new NightlyTaskCleanup());
Test.stopTest();
Assert.areEqual(0, [SELECT COUNT() FROM Task WHERE Id = :oldTask.Id]);
Assert.areEqual(1, [SELECT COUNT() FROM Task WHERE Id = :recentTask.Id]);
}
}Test data for a batch must respect one restriction. In a test, Database.executeBatch runs only a single execute call. The records in start must therefore fit into one scope, which is 200 in NightlyTaskCleanup. If you insert more than 200 matching records, some stay unprocessed and the assertions fail. Test the batch's per-chunk logic with a small data set. Check scale separately in a sandbox with realistic data volumes.
The batch class deserves its own test too. Call Database.executeBatch(new ArchiveOldTasksBatch(), 200) in a start/stop block, and the scheduled class's test then only needs to prove that the batch was started.
Common failures
| Symptom | Likely cause | Fix |
|---|---|---|
| Assertion fails on unchanged records | Asserted before `Test.stopTest()` | Move result assertions after `stopTest` |
| `Based on configured schedule, the given trigger will never fire` | Cron expression names a date in the past | Use a far-future year such as 2099 |
| Query in the job returns nothing | Test data missing, or `CreatedDate` not backdated | Insert data in the test and call `Test.setCreatedDate` |
| Only part of the data is processed by a batch | More records than one scope in a test | Insert no more records than the scope size |
| `System.NullPointerException` in `execute` | Job reads the context and the test passed `null` | Schedule the job through `System.schedule`, or move logic out of `execute` |
| `MIXED_DML_OPERATION` error | Setup objects and other records created in one transaction | Insert setup records inside `System.runAs` |
| Job passes in the test and fails in production | Test user has broader access than the scheduling user | Use `System.runAs` with a restricted user |
Edge cases to cover
- Empty result. Run the job with no matching records. A job that assumes
stale[0]exists fails here, and the failure is costly in production because it repeats on every run. - The
LIMIT 200boundary.EscalateStaleCasesprocesses at most 200 records per run. A test with 201 stale cases confirms that exactly 200 change, and that the extra case is left for the next run. That is a deliberate design choice, so write the test to document it. - Bulk data. Insert 200 records in one test to prove the job has no SOQL or DML inside a loop.
- Callouts. Scheduled
executecannot make callouts directly. If your job starts a callout from a queueable or future method, register a mock withTest.setMockbeforeTest.stopTest(). - Running user. A scheduled job runs as the user who scheduled it. Tests run as the test user unless you wrap the code in
System.runAs. UserunAswhen the job depends on sharing, field-level security or user-specific settings.
A checklist for a scheduled job's tests
- One test that goes through
System.scheduleand checks the outcome afterTest.stopTest(). - One test that checks the
CronTriggerfields beforeTest.stopTest(). - Tests of the underlying logic, with records that must change and records that must not.
- A test for the empty case and for the limit boundary.
- Distinct job names in tests, so that each test is easy to identify when you read the
CronTriggerlist.
Exercise
A test schedules EscalateStaleCases with the expression '0 0 0 15 3 ? 2099' between Test.startTest() and Test.stopTest(). Where should assertions about the escalated cases go, and why does the job run even though the date is in 2099?
Show answer
The assertions go after Test.stopTest(). At stopTest the framework runs all asynchronous work collected since startTest, including scheduled jobs, synchronously, regardless of the cron date. The date only matters for the CronTrigger record, so assertions about TimesTriggered and NextFireTime belong before stopTest.
Exercise
Your test inserts 250 closed tasks older than a year, schedules NightlyTaskCleanup, and calls Test.stopTest(). Only 200 of them are deleted. Why, and how do you fix the test?
Show answer
A test runs only one execute call of a batch. The scope size is 200, so only the first 200 records are processed. Reduce the test data to 200 records or fewer, and test larger volumes in a sandbox.
Exercise
Write the assertions that check a job scheduled as '0 0 0 15 3 ? 2099' has not yet run, using the CronTrigger ID in jobId. Which fields do you query?
Show answer
Query CronExpression and TimesTriggered from CronTrigger WHERE Id = :jobId. Then call Assert.areEqual('0 0 0 15 3 ? 2099', ct.CronExpression) and Assert.areEqual(0, ct.TimesTriggered) before Test.stopTest(). You can also check NextFireTime is not null.