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
Pranav S SanvatsarkarPranav S Sanvatsarkar 

Exception: No more than one executeBatch can be called from within a test method

Hello there,

I have written two triggers - on Contact and User. Contact updates Users and User updates Contacts. I have handled MIXED DML thing using Queueable Apex. Now I am testing invokability of Queueable Apex from Batches. So, I have written  single Batch class that updates both Contacts and Users as per the query passed to the class.

I am testing this batchable class one by one for Contact and User update. I wrote batch calling in one test method first but it gave the error - Exception:  No more than one executeBatch can be called from within a test method. So, I wrote seperate methods for Contact Update and User updates. Tried executing test class in both synchronous and asynchronous modes. First method gets executed well. However, it gives exception while executing second method - Exception:  No more than one executeBatch can be called from within a test method.

Am I missing any limitation or logic?

Thanks in advance.
NagendraNagendra (Salesforce Developers) 
Hi Pranav,

Description


Issue : System.UnexpectedException: No more than one executeBatch can be called from within a test method.

Causes: Might be we are processing more than 200 records in test class for the batch apex.

Resolution

Workarounds : 

=============

>> Try to pass the less than 200 records in test class.

>> What you have to consider is using the Test.isRunningTest to bypass the code starting the second job in this context. Meaning that you will have to test your second batch job in a separate test to get coverage and assert behaviour. In doing so you will obviously have to reproduce manually in the test code the state in the database the second job expects. Not ideal, but should work.

 
The following is an example of the change to avoid the second batch job being executed during test execution.
 
 
public void finish(Database.BatchableContext)
{
    if(!Test.isRunningTest)
         Database.executeBatch(new MySecondBatchJob));
}


>> Enclose the executeBatch in Test.startTest() and Test.stopTest()

>> always try to use @SeeAllData=false

Please mark this as solved if the information helps so that it gets removed from the unanswered queue and becomes a proper solution which results in helping others who are really in need of it with similar issue.

Best Regards,
Nagendra.P