[SalesForce] error from test method – “apex job is already scheduled for execution”

I have a batch apex which starts itself after x mins.
this is done in finish() method using , system.scheduleBatch() method.

below is how the batch looks like,

global class my_ProcessPurge_Batch implements Database.Batchable<sObject> {

    global String query;

    global my_ProcessPurge_Batch() {
     //initialize query string here         
    }

    global Database.QueryLocator start(Database.BatchableContext BC) {
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableContext BC, List<sObject> scope) {    
        //some DML statements here          
    }

    global void finish(Database.BatchableContext BC) {
       //send email of the result
      //schedule next batch
      my_ProcessPurge_Batch nextBatch = new my_ProcessPurge_Batch();
      //job should start executing after 24 hrs
      //scope is 1000
      System.scheduleBatch(nextBatch, 'my_ProcessPurge_Batch', 1440, 1000);     
    }
}

I am trying to test this batch. My test method is as follows,

@isTest static void testProcessPurge() {
    Test.startTest();
    //populate test data
    //start batch
    my_ProcessPurge_Batch purgeBatch = new my_ProcessPurge_Batch();
    database.executeBatch(purgeBatch);
    Test.stopTest();
}

I am receiving error –

System.AsyncException: The Apex job named "my_ProcessPurge_Batch" is
already scheduled for execution.

Error is thrown in the finish() method when I call database.executeBatch() method

There is no other batch running in my org with this name. I also tried to change the name of the
batch but it didn't help.

I can run the same database.executeBatch() method successfully as anonymous code.
It only fails from test method.

any idea what is causing this error and how can I fix it ?

I can use isRunningTest() method and ignore the execution of executeBatch() method but I don't think that answers the question.

Also, if I manage to skip the method call using isRunningTest(), would this cause issue during production deployment when I already have job with the same name already scheduled ?

Best Answer

please find the solution of your question error from test method - “apex job is already scheduled for execution”

@isTest static void testProcessPurge() {
Test.startTest();
//populate test data
//start batch
for ( AsyncApexJob aJob : [ Select id ,Status from AsyncApexJob] )
{
System.AbortJob(aJob.Id);
}
    my_ProcessPurge_Batch purgeBatch = new my_ProcessPurge_Batch();
    database.executeBatch(purgeBatch);
    Test.stopTest();
}