2
  1. How do we write a test class for a schedule batch to run / schedule the schedule batch immediately (without using con expression).

    For example: Schedule batch is as below.

     global class scheduleexample implements Schedulable {
     global void execute(SchedulableContext sc) {
        batchclass batch = new batchclass(); 
        database.executebatch(batch);
       }
     }
    
  2. When a schedule class is associated with a batch class, is it necessary to write two separate test classes for batch and schedule class or can I just write a test class for schedule class and cover the code for the batch class as well ?

1 Answer 1

5

This is one of those situations you'll want to look at the Test.startTest(); and Test.stopTest(); directives.

Generally you will wrap your asynchornous calls in your test class within these blocks. For example:

Account a = new Account(Name = 'Testing Account');
Test.startTest();
    System.schedule('Schedule Name', CRON_EXP, new ScheduleableClass());
Test.stopTest();

Note: Indenting here isn't technically right, but I see many people do this, so... why not...

What happens, is that the test will stop at the Test.stopTest() call until all asynchronous calls have finished from within that block.

Since your schedule class is calling a batch job, then you will find that you have created a asynchronous task that the test will stop and wait for to finish before proceeding. i.e. it will test both your Schedule and Batch class.

Is this the best practise way of writing the test? Depends who you talk to. I like to test my schedule method separately from the batch execution purely to make my life debugging a little bit easier. If your schedule class changes, and you have multiple batch methods, then you will have to edit each test, where if you test it separately, you only have to edit it in one place

1
  • Thanks for the explanation. It definitely makes sense and also gave an insight. Keep sharing the knowledge.
    – Rajesh
    Jun 3, 2015 at 0:19

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.