Wednesday, July 11, 2012

Testing Schedulable classes

Apex Developer's Guide has a sample on testing Schedulable classes.  This is what they say about when your stuff in the Execute( ) method actually gets run in your test code.

"...when you test scheduled Apex, you must ensure that the scheduled job is finished before testing against the results. Use the Test methodsstartTest and stopTest around the System.schedule method to ensure it finishes before continuing your test. All asynchronous calls made after the startTest method are collected by the system. When stopTest is executed, all asynchronous processes are run synchronously. If you don't include the System.schedule method within the startTest and stopTest methods, the scheduled job executes at the end of your test method forApex saved using Salesforce.comAPI version 25.0 and later, but not in earlier versions."

What not mentioned was, the execution seems to be done not through the regular "channel" if you will, because there's no record of the execution in the CronTrigger object.  Therefore if you do this verification after stopTest( ):

        ct = [SELECT id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
        System.assertEquals(1, ct.TimesTriggered);

you are going to get a failure because ct.TimesTriggered would be 0.  So far I don't think this subtle difference has an impact on actual testing needs, but who knows...

No comments:

Post a Comment