I am trying to write a test for my trigger that will queue up some job, unfortunately according to Salesforce, tests can't have chain-able queues.
https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_queueing_jobs.htm
You can’t chain queueable jobs in an Apex test. Doing so results in an error. To avoid getting an error, you can check if Apex is running in test context by calling Test.isRunningTest() before chaining jobs.
So when I run my test I get this error:
System.AsyncException: Maximum stack depth has been reached.
I need to find some way to get around this.
One way I was thinking is to let the trigger know that it's a test, so that it won't queue up the job. Here is my current code:
My Trigger class:
trigger MyTrigger on MyObj(after insert) {
String CRON_EXP = '0 0 0 ? * * *';
MyObjScheduler schedule = new MyObjScheduler ();
String jobId = System.schedule('MyTrigger', CRON_EXP, schedule);
}
My Scheduler Class:
global class MyObjScheduler implements Schedulable {
global void execute(SchedulableContext ctx) {
// Other business logic
MyObjQueueableJob curJob = new MyObjQueueableJob ();
System.enqueueJob(curJob);
}
}
My Queueable
public class MyObjQueueableJob implements Queueable {
public void execute(QueueableContext context) {
// Other business logic
System.enqueueJob(otherJobs);
} }
If there is a way to communicate with Trigger, then I can just write it like this:
trigger MyTrigger on MyObj(after insert) {
String CRON_EXP = '0 0 0 ? * * *';
Boolean IsTest = false; // How to change this to true?
MyObjScheduler schedule = new MyObjScheduler ();
if (!IsTest) {
String jobId = System.schedule('MyTrigger', CRON_EXP, schedule);
}
}
Is this possible?
if(Util.isQueueable()) {System.enqueueJob(..);}
,if (Util.isSchedulable()) {System.schedule(..);}
so the code runs correctly in either test or prod context. You can use the Limits class methods in the Util.isXXX methods