Sample Batch job
global class AccountUpdateBatchJob implements Database.Batchable<sObject>
{
global Database.QueryLocator start(Database.BatchableContext BC) {
String query = 'SELECT Id,Name FROM Account';
return Database.getQueryLocator(query);
}
global void execute(Database.BatchableContext BC, List<Account> scope) {
for(Account a : scope)
{
a.Name = a.Name + 'Updated by Batch job';
}
update scope;
}
global void finish(Database.BatchableContext BC) { }
}
Scheduler Class For Batch Apex
global class AccountUpdateBatchJobscheduled implements Schedulable { global void execute(SchedulableContext sc) { AccountUpdateBatchJob b = new AccountUpdateBatchJob(); database.executebatch(b); } }
Test Class for Scheduler Class
@isTest private class AccountUpdateBatchJobscheduledTest { static testmethod void schedulerTest() { String CRON_EXP = '0 0 0 15 3 ? *'; // Create your test data Account acc = new Account(); acc.name= 'test'; insert acc; Test.startTest(); String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, new AccountUpdateBatchJobscheduled()); CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId]; System.assertEquals(CRON_EXP, ct.CronExpression); System.assertEquals(0, ct.TimesTriggered); Test.stopTest(); // Add assert here to validate result } } |
Please check below post for Batch job
1) http://amitsalesforce.blogspot.com/2016/02/batch-apex-in-salesforce-test-class-for.html
Please check below post for more detail
1) https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_scheduler.htm
Thanks,
Amit Chaudhary
Hi Amit,
ReplyDeleteThis is great and I use a similar test class format which works for one class that I wrote but I used it again for another and I cannot get the scheduled batch to fire in the test class. I posted it here: https://salesforce.stackexchange.com/questions/257958/test-class-for-a-scheduled-batch-is-not-firing-the-batch
Any ideas?
It worked for me. Thanks
ReplyDelete