8

I have an Queueable class which enqueues second job and now i want to write test class for the Queueable class. How should I cover my code in the second enqueued class of my test class?

As specified in the documentation :

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.

Source

2 Answers 2

6

There's two general ways to go about this. First, you could choose to simply "emulate" the chaining:

Test.startTest();
Test.stopTest(); // So no chains will execute...
Queueable q1 = new MyFirstQueueable();
q1.execute(null);
Queueable q2 = new MySecondQueueable(q1);
q2.execute(null);

The second method is to test each class independently, and guard against chained calls in a unit test. Note that this means you cannot achieve 100% code coverage.

public class MyFirstQueueable Implements Queueable {
    public void execute(QueueableContext context) {
        // Do stuff
        if(!Test.isRunningTest()) {
            System.enqueueJob(new MySecondQueueable(this));
        }
    }
}
4
  • if i go with the first method, my second job has some parameters sent as System.enqueueJob(new MySecondQueueable(fldId,false,null)); and if i call it as Queueable q2 = new MySecondQueueable(q1); it gives me erros ": Constructor not defined: ". obviously because the function declaration doesn't match.. is it necessary to send q1 to second job ? Nov 22, 2016 at 8:33
  • @sfdeveloper No, it was only meant to be illustrative. You need to use whatever parameters are appropriate for your class.
    – sfdcfox
    Nov 22, 2016 at 14:57
  • is it possible to actually setup a QueueableContext context to pass in? I have a usecase where I'm using the job idea for error logging.
    – NSjonas
    Jun 23, 2018 at 5:27
  • 1
    @NSjonas I don't think you can, actually. It looks pretty locked down. Just to be safe, though, I suggest you ask a new question. Just because I don't have answer doesn't mean that someone else doesn't.
    – sfdcfox
    Jun 23, 2018 at 5:31
1

You can now use maximumQueueableStackDepth property of the AsyncOptions class to limit the depth of the queueable job stack, which represents the maximum number of chained jobs that can be added to the stack. If the limit is reached, any further attempt to add a job to the stack will result in a System.AsyncException.

You can check here for more details: https://hellosnl.blogspot.com/2024/01/salesforce-apex-creating-apex-test-class-chaining-queueable-job.html

You must log in to answer this question.

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