0

how to create test class for scheduled?

Apex class:

global class InactivitySchedule implements Schedulable{
   global void execute(SchedulableContext sc){
       AssignCaseToQueue caseToQueue = new AssignCaseToQueue();
       Database.executeBatch(caseToQueue, 100);   
   }
}

Test class:

@isTest
private class InactivitySchedule{
  static testMethod void unitTest(){
   //what should i use for cover
  }
}

2 Answers 2

1

You can use CronTrigger object to query to assert whether scheduler runs or not.

Test.startTest();

Datetime dt = Datetime.now().addMinutes(2);
String CRON_EXP = '0 '+ dt.minute() + ' * ' + dt.day() + ' ' + dt.month() + ' ? ' + dt.year();
String jobId = System.schedule('Sample_Heading', CRON_EXP, new InactivitySchedule() );

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();
2

You should create a Job then specify it's Cron Expression and then simply use System.schedule method. To make Cron Expression you can use CronMaker. CronMaker is the easiest way generate a Cron Expression. Refer below code:

@isTest
    private class InactivitySchedule{
      static testMethod void unitTest(){
        Test.StartTest();
        InactivitySchedule  sh1 = new InactivitySchedule ();
        String sch = '0 0 23 * * ?'; 
        Id jobId = system.schedule('Test Job', sch, sh1); 
        System.assertNotEquals(null,jobId );
        AsyncApexJob a = [Select Id, Status ,NumberOfErrors 
           from AsyncApexJob where Id = :jobId ];
        System.assert(a.NumberOfErrors == 0);
        Test.stopTest();
      }
    }
2
  • and for assert ? Commented Mar 8, 2017 at 6:41
  • @cloudZigZag modified my code. System.schedule returns a JobId which can be used to check if it's scheduled or not Commented Mar 8, 2017 at 6:44

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .