Skip to content

Instantly share code, notes, and snippets.

@RatanPaul
Forked from mjgallag/BatchJob.cls
Created January 5, 2016 10:11
Show Gist options
  • Save RatanPaul/5019bdf749b83b9e524e to your computer and use it in GitHub Desktop.
Save RatanPaul/5019bdf749b83b9e524e to your computer and use it in GitHub Desktop.
Scheduled Batch Job Test Example
global class BatchJob implements Database.Batchable<Account> {
global Account[] start(Database.BatchableContext batchableContext) {return new Account[]{};}
global void execute(Database.BatchableContext batchableContext, Account[] accounts) {}
global void finish(Database.BatchableContext batchableContext) {}
}
@isTest class ScheduledBatchJobTests {
@isTest static void scheduledBatchJobTest() {
final Id cronTriggerId;
// Even in 24.0, with SeeAllData set to false by default, existing CronTrigger records are visible, this is a SFDC bug.
// Therefore, to avoid 'System.AsyncException: The Apex job named "ScheduledJob" is already scheduled for execution' abort all existing Scheduled Jobs.
// Cannot look for and abort only "ScheduledJob" because of an SFDC bug where Name Field is not exposed in CronTrigger, thus the abort all loop.
for (CronTrigger cronTrigger : [SELECT Id FROM CronTrigger]) System.abortJob(cronTrigger.Id);
// AsyncApexJob correctly follows SeeAllData=false as this count returns 0 even if existing Batch Job history in org.
System.assertEquals(0, [SELECT COUNT()
FROM AsyncApexJob
WHERE ApexClassId IN (SELECT Id FROM ApexClass WHERE NamespacePrefix = null AND Name = 'BatchJob')]);
Test.startTest();
cronTriggerId = System.schedule('ScheduledJob', '0 0 * * * ?', new ScheduledJob());
Test.stopTest();
System.assertEquals(1, [SELECT COUNT()
FROM AsyncApexJob
WHERE ApexClassId IN (SELECT Id FROM ApexClass WHERE NamespacePrefix = null AND Name = 'BatchJob')]);
// This proves that the Scheduled Job has kicked off the Batch Job. You may now proceed to test Batch Job itself directly in its own test method.
System.assertEquals('Queued', [SELECT Status
FROM AsyncApexJob
WHERE ApexClassId IN (SELECT Id FROM ApexClass WHERE NamespacePrefix = null AND Name = 'BatchJob')].Status);
}
}
global class ScheduledJob implements Schedulable {
global void execute(SchedulableContext schedulableContext) {Database.executeBatch(new BatchJob());}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment