function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
RajiiiRajiii 

Test method coverage problem: No more than one executeBatch can be called from within a testmethod

 I have written a test method for batch apex. i am facing issue like '"No more than one executeBatch can be called from within a testmethod. Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation."'

 

       Test.startTest();
          PageSubsNotification job = new PageSubsNotification();    
          job.mysoql = 'SELECT ContentDocumentId, Title FROM ContentVersion where Portal_Segmentation__c =\'Registered Visitor\' limit 1';         
          ID batchprocessid = Database.executeBatch(job);
        Test.stopTest();

can anybody give me a solution for this. pls

 

 

bvramkumarbvramkumar
If already a batch with same name is running in the org, then you need to delete that in order to execute the test method.
Rahul SharmaRahul Sharma

That error states that, you can only execute a batch class once from a test class. It might be the case that, your org contains more than 200 records or you have mimimised the number of records to the batches.

 

The best solution so far is to limit the query batch class for a test method. 

 

You need to add the highlighted code in the start method(Or in constructor), Just to add the limit clause for limiting number of records passed to batch class.

global class UpdateAccountFields implements Database.Batchable<sObject>{
   global final String Query;
   global final String Entity;
   global final String Field;
   global final String Value;

   global UpdateAccountFields(String q, String e, String f, String v){
             Query=q; Entity=e; Field=f;Value=v;
   }

   global Database.QueryLocator start(Database.BatchableContext BC){
      // Add the limit for test class, for passing limited records to the batch
      if(Test.isRunningTest()) {
          query += ' limit 10';
      }
      return Database.getQueryLocator(query);
   }

   global void execute(Database.BatchableContext BC, 
                       List<sObject> scope){
      for(Sobject s : scope){
          s.put(Field,Value); 
      }      
          update scope;
   }

   global void finish(Database.BatchableContext BC){

   }

}

 Hope it helps.