[SalesForce] System.AsyncException: Maximum stack depth has been reached. while writing in test class

I've got a requirement to perform queueable apex in a trigger my class working fine, but while writing a test class for queueable apex I'm getting an exception. Could anybody can help me.

Trigger example on opportunity(After update){
if(Trigger.isAfter && Trigger.isUpdate){
        System.enqueuejob(new  Oppty_TargetHandlerContainer(Trigger.old));
}
if(Trigger.isAfter && trigger.isUpdate){
           System.enqueuejob(new  Oppty_TargetHandlerContainer(Trigger.new));
 }

}

This my test class

@isTest
public class Oppty_TargetHandlerContainerTest {
//varibale Declaration

static void init(){
    //Initializing the data
    }

    //}
}

//Method to cover opportunity handler.
static testMethod void opportunityTriggerMethod1(){
  init();
  Test.startTest();
   System.enqueuejob(new  Oppty_TargetslogicHandler(opplist));
  Test.stopTest();
  Test.startTest();
   System.enqueuejob(new  Oppty_TargetHandlerContainer(opplist));
  Test.stopTest();
}  
}

The following are the my queueable classes

public class Oppty_TargetHandlerContainer implements Queueable {
@Testvisible
private List<Opportunity> optylist;
public Oppty_TargetHandlerContainer(List<Opportunity> optys) {
    this.optylist = optys;
}
public void execute(QueueableContext qc) {
    System.enqueueJob(new Oppty_TargetslogicHandler(optylist));
}
}

Logic queueable class

public class Oppty_TargetslogicHandler implements Queueable {
//Variable declaration
public Oppty_TargetslogicHandler(List<Opportunity> optys) {
    //storing data in variables
}
public void execute(QueueableContext qc) {
    updating some other object,
    there is a recursive trigger

}
}

Best Answer

In your Oppty_TargetHandlerContainerTest:: opportunityTriggerMethod1() test method, you are running two asynchronous jobs, which is not allowed in a single test method. Only one job can be run per test method.

Put each job into a separate test method function and it should work.

EDIT

The code should look something like this:

static testMethod void opportunityTriggerMethod1(){
   init();

   Test.startTest();
   System.enqueuejob(new  Oppty_TargetslogicHandler(opplist));
   Test.stopTest();
}

static testMethod void opportunityTriggerMethod2(){
   init();

   Test.startTest();
   System.enqueuejob(new  Oppty_TargetHandlerContainer(opplist));
   Test.stopTest();

    // Optional Assert methods to confirm functionality
}  
Related Topic