Sub topic 3
Testing Schedulable Classes
Assume you know basic Apex tests, assertions, and asynchronous Apex types. A schedulable class runs later, so use Test.startTest() and Test.stopTest() to test its scheduling behavior.
Testing Schedulable classes
Schedule the class inside the test window. Use a date far enough in the future to prevent the job from running during the test. Query CronTrigger to verify the schedule. Test the work performed by execute separately, often by calling it directly.
@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 job = [
SELECT CronExpression, TimesTriggered
FROM CronTrigger
WHERE Id = :jobId
];
Assert.areEqual(cron, job.CronExpression);
Assert.areEqual(0, job.TimesTriggered);
}
}Asserting results after `stopTest`
Re-query records after Test.stopTest(). The asynchronous transaction may have changed the database, but an SObject variable created before the job ran still contains its old field values.
Mocking HTTP callouts from async code
Tests cannot make real HTTP callouts. Register an HttpCalloutMock before queuing the job:
Test.setMock(HttpCalloutMock.class, new StatusCalloutMock());
Test.startTest();
System.enqueueJob(new CalloutJob());
Test.stopTest();The job receives the fake response when it runs.
Testing chained Queueable jobs
Only the first Queueable job queued inside the test window is guaranteed to run. Do not assume an entire chain executes. Test each link separately, or assert that the first job created the expected next-job state.
Delivering platform events
Publish the event during the test, then deliver it explicitly:
Test.startTest();
EventBus.publish(new Account_Event__e(AccountId__c = accountId));
Test.getEventBus().deliver();
Test.stopTest();Assert subscriber effects after delivery.
Pitfalls and limits of the test context
- A test method can use only one
startTestandstopTestpair. - Async work queued before
startTestdoes not run atstopTest. - A batch test normally exercises one
executescope. - Tests have separate transactions and governor limits.
- Keep setup before
startTest; reserve the window for the operation under test.
Exercise
Where should you query a record changed by a Queueable job?
Show answer
After Test.stopTest(), using a fresh SOQL query.