1

I've writtem a test class for my batch class. I've followed everything that was described in this question. Still getting the same error. Can anyone help me to find the problem in my code?

System.UnexpectedException: No more than one executeBatch can be called from within a test method. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation.

Start method

  String queryFields = 'SELECT Id, Name, BM_DPM_Date__c, BM_DPM_FC__c, BM_DPM_RecommendedFT_MH__c, ExtraFT__c, BM_DPM_PartTimeMH_Average__c, ExtraPT__c ';
    String queryObjectAPIName = 'FROM BM_DailyProductivityManagement__c ';
    String queryWhereClause = 'WHERE BM_DPM_Date__c >=: startDate AND BM_DPM_Date__c <=: endDate ';
    String queryOrderby = 'ORDER BY BM_DPM_Date__c ASC';
    
    String query = queryFields + queryObjectAPIName + queryWhereClause + queryOrderby + queryOrderby + (Test.isRunningTest() ? ' LIMIT 200' : '');
    return Database.getQueryLocator(query);

Finish method

   global void finish(Database.BatchableContext dbc){
    if (!Test.isRunningTest()){
        BM_26_CL_FT_Schedule batch = new BM_26_CL_FT_Schedule();
        batch.startDate = startDate;
        batch.endDate = endDate;
        Database.executeBatch(batch, 1);
    }
}

Excerpt from my test class

    System.Test.startTest();
    BM_25_OP_FT_Schedule newBatch = new BM_25_OP_FT_Schedule();
    newBatch.startDate = startDate;
    newBatch.endDate = endDate;
    Database.executeBatch(newBatch, 1);
    System.Test.stopTest();
7
  • Are you using @isTest(SeeAllData=true) in the test class? Apr 25, 2022 at 6:35
  • Nope, @isTest(SeeAllData=false). Thank you SaiPraveen for your response. However, I've figured out the problem by putting 'LIMIT 1'. It worked. Apr 25, 2022 at 6:56
  • You can put limit 200 . But the main issue is you are calling the batch class with batch size as 1 because of which the execute method is excuting more than once. You can put batch size as 200 while calling the batch class from test class Apr 25, 2022 at 6:58
  • Oh, now I got it. Thanks SaiPraveen!!! Apr 25, 2022 at 6:59
  • If you wish to go with that procedure I can post is as answer Apr 25, 2022 at 7:00

2 Answers 2

2

As mentioned in my comments you can also limit it by 200. That may not be the issue. But while you are calling the batch class from test class you are giving batch size as 1 because of which you are having the issue. Instead of that use the batch size as 200 then the issue will be resolved.

0

I solved the problem by changing:

  if (Test.isRunningTest()){
        query += ' LIMIT 200';
    }

TO ->

  if (Test.isRunningTest()){
        query += ' LIMIT 1';
    }

You must log in to answer this question.

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