Sub topic 9
Testing Schedulable classes
This chapter assumes you can write an @IsTest class with assertions and know what a Schedulable class does. It also assumes you have read the earlier chapters on the test window and on how async jobs run at Test.stopTest(). Here you will learn what a scheduled-job test can and cannot verify, and how to test both the scheduling and the job's logic.
What a Schedulable class does
A Schedulable class implements the Schedulable interface and has one method, execute(SchedulableContext). You register it with System.schedule, which takes a job name, a cron expression and an instance of the class. Salesforce then runs execute at the times the cron expression describes.
Scheduled jobs differ from @future methods, Queueable jobs and batches in one way that matters for tests. The job fires on a clock, not because your code queued work. A test cannot wait for a real cron time. So a test of a Schedulable class usually has two separate goals:
- Check that the job can be scheduled and that the schedule is stored correctly.
- Check that the job's
executelogic does the right thing.
You test these two goals in different ways.
Schedule the job and check the CronTrigger
When you call System.schedule, Salesforce creates a CronTrigger record. It holds the cron expression, the next fire time, and how many times the job has run. The test can read this record to confirm the job was scheduled.
public class NightlyJob implements Schedulable {
public void execute(SchedulableContext sc) {
Database.executeBatch(new AccountBatch(), 200);
}
}
@IsTest
private class NightlyJobTest {
@IsTest
static void jobIsScheduled() {
String cron = '0 0 0 15 3 ? 2099';
Test.startTest();
Id jobId = System.schedule('Nightly job test', cron, new NightlyJob());
Test.stopTest();
CronTrigger ct = [SELECT CronExpression, TimesTriggered FROM CronTrigger WHERE Id = :jobId];
Assert.areEqual(cron, ct.CronExpression);
Assert.areEqual(0, ct.TimesTriggered);
}
}The test follows the usual pattern. It calls System.schedule between startTest and stopTest, then queries after stopTest. Two details are worth noting.
- The cron expression uses the year 2099. The job is far in the future, so it will not fire on its own while the test runs. The test checks the stored schedule and nothing else.
TimesTriggeredis 0. The job has not run, because its fire time has not arrived.
The jobId that System.schedule returns is the ID of the CronTrigger record, so you can use it directly in the query.
Reading a cron expression
Apex cron expressions have seven fields. The last one, the year, is optional.
| Position | Field | Allowed values |
|---|---|---|
| 1 | Seconds | 0-59 |
| 2 | Minutes | 0-59 |
| 3 | Hours | 0-23 |
| 4 | Day of month | 1-31 |
| 5 | Month | 1-12 or JAN-DEC |
| 6 | Day of week | 1-7 or SUN-SAT |
| 7 | Year (optional) | 1970-2099 |
In 0 0 0 15 3 ? 2099, the job runs at 00:00:00 on 15 March 2099. The ? in the day-of-week field means "no specific value". Apex requires ? in either the day-of-month or the day-of-week field, because you can set only one of them.
Why scheduled jobs do not run at stopTest
The earlier chapters showed that @future, Queueable and batch work queued in the test window runs at stopTest. A scheduled job behaves differently. The job fires at its scheduled time, and that time lies in the future. Calling Test.stopTest() does not make execute run.
This is why the example above asserts TimesTriggered equals 0. If you expected the job's side effects to appear after stopTest, your assertions would fail, and the failure would be confusing: the job was scheduled correctly, but nothing ran.
The scheduling test proves only that registration works. It does not prove that execute does the right thing.
Test the job logic by calling execute directly
A Schedulable class is an ordinary Apex class. Its execute method is a public method, so a test can create an instance and call it. This runs the logic immediately, with no cron expression involved.
Consider a Schedulable class that does its own work instead of starting a batch:
public class StaleAccountJob implements Schedulable {
public void execute(SchedulableContext sc) {
List<Account> stale = [
SELECT Id FROM Account WHERE Description = null LIMIT 200
];
for (Account a : stale) {
a.Description = 'Needs review';
}
update stale;
}
}
@IsTest
private class StaleAccountJobTest {
@IsTest
static void executeMarksAccounts() {
insert new Account(Name = 'Stale Account');
Test.startTest();
new StaleAccountJob().execute(null);
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Name = 'Stale Account'];
Assert.areEqual('Needs review', result.Description);
}
}The test passes null for the SchedulableContext. This works because the class never reads the context. If your execute calls sc.getTriggerId(), a null context throws a NullPointerException. In that case, schedule the job for real in the test, or move the logic out of execute, as described next.
The call sits inside startTest and stopTest. Direct calls do not need the window to run. The window is still useful here, because the code under test then gets its own fresh set of governor limits, separate from the test's data setup.
Keep execute thin
A common design is to keep execute small and put the work in another class. The Schedulable class then only chooses what to run:
public class StaleAccountService {
public static Integer markStale() {
List<Account> stale = [
SELECT Id FROM Account WHERE Description = null LIMIT 200
];
for (Account a : stale) {
a.Description = 'Needs review';
}
update stale;
return stale.size();
}
}
public class StaleAccountScheduler implements Schedulable {
public void execute(SchedulableContext sc) {
StaleAccountService.markStale();
}
}You then test StaleAccountService.markStale() like any synchronous method, and write one small scheduling test for StaleAccountScheduler. The logic has no dependence on cron timing or on a context object, so it is easy to test.
When execute starts other async work
The NightlyJob example starts a batch from execute. If a test calls execute directly between startTest and stopTest, the batch it queues runs at stopTest, as you saw in the batch chapter. The same single-scope limit applies. So a test of that path should keep its data within one scope of 200 records and assert on the batch's results after stopTest.
@IsTest
private class NightlyJobExecuteTest {
@IsTest
static void executeStartsBatch() {
insert new Account(Name = 'Nightly Target');
Test.startTest();
new NightlyJob().execute(null);
Test.stopTest();
Account result = [SELECT Description FROM Account WHERE Name = 'Nightly Target'];
Assert.areEqual('Batch processed', result.Description);
}
}Here NightlyJob.execute calls Database.executeBatch inside the test window. At stopTest, the batch runs synchronously, and the assertion sees the changed record.
Choosing between the two approaches
| Question | Schedule with System.schedule | Call execute directly |
|---|---|---|
| Does the cron expression parse? | Yes | No |
| Is a CronTrigger created? | Yes | No |
| Does the job's logic run? | No | Yes |
| Needs a SchedulableContext? | Provided by the platform | Pass `null` or avoid using it |
Most Schedulable classes need both tests. One short test checks scheduling. One or more tests check the logic.
Common mistakes
- Expecting execute to run at stopTest. It does not. Scheduled jobs wait for their fire time. Assert on the
CronTrigger, or callexecuteyourself. - Using a near-future cron expression. The expression must be valid, and a date in the past or a malformed string causes an exception. A far-future year such as 2099 is a safe, readable choice.
- Reading the context in execute and passing null. A
nullcontext fails ifexecuteuses it. Keepexecuteindependent of the context, or schedule the job for real. - Scheduling the same job name twice. Job names do not have to be unique in tests, but giving each test a clear name makes failures easier to read.
- Skipping the CronTrigger check. If you never query the
CronTrigger, the scheduling test proves nothing, becauseSystem.schedulesimply returned an ID.
Exercise
A test calls System.schedule with a cron expression for the year 2099 between Test.startTest() and Test.stopTest(). After stopTest, it asserts that an Account's Description was changed by the job's execute method. The assertion fails. Why, and how do you fix the test?
Show answer
The job has not run. A scheduled job fires at its scheduled time, and stopTest does not force it to run, unlike @future, Queueable and batch work. The CronTrigger shows TimesTriggered of 0. To fix it, split the test in two. One test schedules the job and asserts on the CronTrigger (CronExpression and TimesTriggered equal to 0). A second test creates the job instance, calls execute directly (passing null for the SchedulableContext if execute does not use it), and asserts on the changed Account after re-querying it.
Exercise
Why does a design that keeps execute thin, with the work in a separate service class, make a Schedulable class easier to test?
Show answer
The service method is an ordinary synchronous method, so a test can call it directly and assert on the results. It does not depend on cron timing or on a SchedulableContext. The Schedulable class then needs only one short test that schedules it and checks the CronTrigger.