-1

I can't understand how to write a test class for a batch scheduler. Here is my scheduler:

global class UltimateParent18Digit_BatchJobScheduler implements Schedulable {
public static String sched = '0 00 00 * * ?'; //Every Day at Midnight

global static String scheduleMe() {
    UltimateParent18Digit_BatchJobScheduler SC = new UltimateParent18Digit_BatchJobScheduler();
    return System.schedule('OARs sync every day at midnight', sched, SC);
}

global void execute(SchedulableContext sc) {
    UltimateParent18Digit_BatchJob myBatchObject = new UltimateParent18Digit_BatchJob();
    Id batchId = Database.executeBatch(myBatchObject, 200);
}

}

Here is my test class:

@isTest
public class UltimateParent18Digit_BatchSchr_Test {

@isTest
static void testScheduler () {
            
    Test.startTest();
    
    String jobId = System.schedule('testBasicScheduledApex',
  UltimateParent18Digit_BatchJobScheduler.sched, 
     new UltimateParent18Digit_BatchJobScheduler());
    
    Test.stopTest();
}
}

It compiles, but it only gives me 57% code coverage.

1 Answer 1

2

You didn't call the scheduleMe method:

Test.startTest();
UltimateParent18Digit_BatchJobScheduler.scheduleMe();
Test.stopTest();
3
  • Thanks @sfdcfox, helped me figure it out again! Here is what I've learned. The middle part of my scheduler scheduleMe() has to be commented (removed). You use it only once (when you schedule the batch). When a job scheduled, it can't be scheduled again, which is what the test class is trying to do. With that said, If I use the code you posted, it will give me an error ".. already scheduled". So, the only part that has to be tested is the execute().
    – Slava
    Apr 15 at 18:21
  • @Slava The job name has to be unique. I'd suggest you make the job name configurable for your unit test, something like @TestVisible static String jobName = 'OARs sync every day at midnight'; and in your unit test, UltimateParent18Digit_BatchJobScheduler.jobName = 'Unit Test for OARs Sync'; UltimateParent18Digit_BatchJobScheduler.scheduleMe();
    – sfdcfox
    Apr 15 at 19:14
  • Job name configurable, makes sense. Thanks
    – Slava
    Apr 15 at 23:10

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.