Sub topic 9
Testing Schedulable classes
This chapter assumes you can write a basic @IsTest class and that you know what Schedulable Apex does. You should also know how Test.startTest and Test.stopTest bound the test window, which earlier chapters covered.
What is different about scheduled jobs
A Schedulable class runs at a time set by a cron expression. A test cannot wait for that time. Two questions are worth testing, and they need different techniques:
- Does the job get scheduled with the right cron expression?
- Does the job's
executemethod do the right work?
The first question is answered by calling System.schedule inside the test window. The second is answered by calling execute directly.
Testing that the job is scheduled
The class below schedules a batch job. The test schedules it with a cron expression far in the future, so it never fires during the test run.
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);
}
}System.schedule returns the Id of a CronTrigger record. Re-query that record after stopTest to check what the platform stored. TimesTriggered is 0 because the job has not run, and the 2099 date ensures it will not.
The class AccountBatch comes from the Batch Apex chapter. It must exist in your org for this example to compile.
Parts of a cron expression
The expression has seven fields, separated by spaces. The last one, the year, is optional.
| Position | Field | Example value |
|---|---|---|
| 1 | Seconds | 0 |
| 2 | Minutes | 0 |
| 3 | Hours | 0 |
| 4 | Day of month | 15 |
| 5 | Month | 3 |
| 6 | Day of week | ? |
| 7 | Year (optional) | 2099 |
The ? means "no specific value". Salesforce requires it in either the day-of-month or the day-of-week field.
Testing what the job does
Scheduling a job in a test does not run its execute method. To test the logic, create an instance and call execute yourself. A null context is fine when the method does not read it.
@IsTest
private class NightlyJobExecuteTest {
@IsTest
static void executeProcessesAccounts() {
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 5; i++) {
accounts.add(new Account(Name = 'Nightly ' + i));
}
insert accounts;
Test.startTest();
new NightlyJob().execute(null);
Test.stopTest();
Integer processed = [SELECT COUNT() FROM Account WHERE Description = 'Batch processed'];
Assert.areEqual(5, processed);
}
}execute starts a batch job. Because that call happens inside the test window, the batch runs at stopTest, and the assertion afterward sees its results. This reuses what you learned about batch testing: the data stays within one scope of 200 records.
The flow below shows the two paths.
Common mistakes
- Using a near-term cron expression. The job still does not run in the test. A date far in the future keeps the intent clear.
- Expecting
System.scheduleto runexecute. It only creates theCronTrigger. Callexecutedirectly to test the logic. - Scheduling outside the test window. Keep
System.schedulebetweenstartTestandstopTest, like other async calls. - Reusing a job name. Scheduled job names appear in the org's job list. Use a distinct name in each test to keep the intent readable.
Exercise
A test calls System.schedule with a valid cron expression between startTest and stopTest, then asserts that a record was updated by the job's execute method. The assertion fails. Why, and how do you fix it?
Show answer
System.schedule only creates a CronTrigger. It does not run execute, so the record is never changed. To test the job's logic, call execute on a new instance of the class directly inside the test window, then re-query the record after stopTest. Use System.schedule in a separate test to check the CronTrigger.