function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
bretondevbretondev 

Schedulable Class : How to cover execute() method by test?

Hello

I have a schedulable class that implements Schedulable interface and conatins execute() method.
Now I have created Test Class but I do not manage to reach execute() method from the test class.
I have a lot of code in execute() that needs to get covered by tests.

I have seen lots of posts and official documentation, but none of the examples reach the execute method.

For example, from the official documentation :
 
@istest
class TestClass {

   static testmethod void test() {
   Test.startTest();

      Account a = new Account();
      a.Name = 'testScheduledApexFromTestMethod';
      insert a;

      // Schedule the test job

      String jobId = System.schedule('testBasicScheduledApex',
      TestScheduledApexFromTestMethod.CRON_EXP, 
         new TestScheduledApexFromTestMethod());

      // Get the information from the CronTrigger API object
      CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, 
         NextFireTime
         FROM CronTrigger WHERE id = :jobId];

      // Verify the expressions are the same
      System.assertEquals(TestScheduledApexFromTestMethod.CRON_EXP, 
         ct.CronExpression);

      // Verify the job has not run
      System.assertEquals(0, ct.TimesTriggered);

      // Verify the next time the job will run
      System.assertEquals('2022-09-03 00:00:00', 
         String.valueOf(ct.NextFireTime));
      System.assertNotEquals('testScheduledApexFromTestMethodUpdated',
         [SELECT id, name FROM account WHERE id = :a.id].name);

   Test.stopTest();

   System.assertEquals('testScheduledApexFromTestMethodUpdated',
   [SELECT Id, Name FROM Account WHERE Id = :a.Id].Name);

   }
}

It works but it is not sufficient in my case, beacuse it only asserts that the job is in the Scheduled Jobs queue.
It actually does not trigger the execute() method.

Please how can I reach execute() ?

 
Best Answer chosen by bretondev
Steven NsubugaSteven Nsubuga
Schedulable class executes immediately after Test.stopTest();
Simply add an Assert to check that the expected change was effected by the Schedulable class

All Answers

Steven NsubugaSteven Nsubuga
Schedulable class executes immediately after Test.stopTest();
Simply add an Assert to check that the expected change was effected by the Schedulable class
This was selected as the best answer
bretondevbretondev
I was able to find a workaround by moving all my code that was in my execute() method to another private method that takes no argument.
This way I could call the new method from my test class and get all the lines covered.
Therefore I could not check your last statement.
I believe you are right though, so I will mark it as Best Answer.