Test class is creating ApexAsyncJob records

I have a unit test, where im testing, if the class, which implements Schedulable interface is being scheduled using System.schedule() method. The problem is, that when Running this test class, it creates ApexAsyncJob and now i can’t modify that test class. Im getting “This schedulable class has jobs pending or in progress” error upon saving the class.

enter image description here

The test method looks like this:

@isTest
public static void testScheduleJob() {


   Test.startTest();
       Id cronJob = OrderResubmitService.scheduleJob();  
   Test.stopTest();        
} 

And the OrderResubmitService method looks like this:

public static Id scheduleJob() {
    OrderResubmitSchedulable ors = new OrderResubmitSchedulable();
    String sch = calculateNextCronTime();

    return System.schedule(CRON_JOB_NAME, sch, ors);          
}

Schedulable class:

global class OrderResubmitSchedulable implements Schedulable {    

    global OrderResubmitSchedulable() {

    }

    global void execute(SchedulableContext SC) {        

        resubmitOrder();                    
        System.abortJob(SC.getTriggerId());
    }

    @future(callout=true)
    private static void resubmitOrder() {

        // make an http-call      
        String msg = OrderUtilities.submitOrder();

        // check if order is still being processed by SAP        
        if (msg == '202' || msg == '210') {
            // check if we have still some attempts left and we dont have already 100 scheduled jobs
            Boolean governorLimitOK = OrderResubmitService.canScheduleAnotherJob('OrderResubmitSchedulable');
            if (governorLimitOK) {                    
                OrderResubmitService.scheduleJob();   
            }           
        }
    }    

Answer

I suspect you have an instance of the Job running outside of the testing context.

Try the following SOQL query:

Select Id,JobType,ApexClassId, ApexClass.Name, Status,JobItemsProcessed,TotalJobItems,NumberOfErrors,CompletedDate,MethodName,ExtendedStatus,ParentJobId,LastProcessed,LastProcessedOffset from AsyncApexJob where Status not in ('Completed', 'Aborted')

I tried your sample test method and class and couldn’t get it to lock up the associated classes. Even with the future method rescheduling the class.

Attribution
Source : Link , Question Author : Martin.Kona , Answer Author : Daniel Ballinger

Leave a Comment