[SalesForce] How to write a unittest for scheduled apex

I have a scheduler for a callout class. I am trying to write a unittest for my scheduler but do not know how to test the execute part

Class

 global class or_guestsSchedulable implements Schedulable{

    global void execute(SchedulableContext sc) 
    {        
   or_service.getGuests();
    }    
}

Unittest

private class or_guestsSchedulableTest {

    private static testMethod void or_guestsSchedulable() {

    Test.startTest();
        Datetime dt = Datetime.now().addMinutes(1);
        String CRON_EXP = '0 '+ dt.minute() + ' * ' + dt.day() + ' ' + dt.month() + ' ? ' + dt.year();
        or_guestsSchedulableTest.execute('Sample_Heading', CRON_EXP, new  or_guestsSchedulable () );   
        Test.stopTest();
    }
    }

Update Unittest

private class or_guestsSchedulableTest {

private static testMethod void or_guestsSchedulableMethodTest() {

Test.startTest();
      String jobId = System.schedule('Sample_Heading', CRON_EXP, new or_guestsSchedulable());  
    Test.stopTest();
}
}

Best Answer

You are struggling with the basic things, You can learn from here:-

  1. Schedule Jobs Using the Apex Scheduler
  2. Apex Scheduler

In your case, to schedule it in the test class, the syntax will be like this:-

// Schedule the test job
        String jobId = System.schedule('Sample_Heading',
            CRON_EXP, 
            new or_guestsSchedulable());

You are doing it in the wrong way.

or_guestsSchedulableTest.execute('Sample_Heading', CRON_EXP, new  or_guestsSchedulable () );

For Scheduled Apex you must also ensure that the scheduled job is finished before testing against the results. To do this, use startTest and stopTest again around the System.schedule method, to ensure processing finishes before continuing your test.

After you implement a class with the Schedulable interface, use the System.Schedule method to execute it. The scheduler runs as system—all classes are executed, whether or not the user has permission to execute the class.

The System.Schedule method takes three arguments: a name for the job, an expression used to represent the time and date the job is scheduled to run, and the name of the class.

For Cron expression, You can use Online tool available which make sure you don't have any error. I think your Cron statement will not work. Use below link to get correct one:-

Cron Maker

Note:- please change your method name or_guestsSchedulable in the test class.

Update:- You need to Create one variable where you will store the Cron value which will tell the test class when to schedule the class.

example:-

// Seconds Minutes Hours Day_of_month Month Day_of_week optional_year
String CRON_EXP = '20 30 8 10 2 ?';

As i told, generate it link i have provided above.

Related Topic