3

I'm trying to run with a unit test a batch apex process where I'm calling the same class 5 times.

For example:

public class MyBatch implements Database.Batchable<SObject>
{
    ...
    public void finish(Database.BatchableContext ctx)
    {
        Integer numOfMyObjs = [Select count() from MyObject__c Where <Any Condition> Limit 1];
        if (numOfMyObjs > 0)
        {
            MyBatch myBatch = new MayBatch(...);
            Database.executeBatch(myBatch);
        }
    }
}

Test Class

public class MyUnitTest
{
    @isTest
    static void testMyBatch()
    {
        Test.startTest();
        MyBatch myBatch = new MayBatch(...);
        Database.executeBatch(myBatch);
        Test.stopTest();
    }
}

And I'm getting the following error: System.LimitException: Too many async jobs enqueued for this apex test context

Any ideas?

  • can you tell what business scenario you are trying to achieve by calling the same class 5 times? – Bforce Jul 3 '14 at 11:49
  • It's recursively calling itself, called a "chain batch". – sfdcfox Jul 3 '14 at 11:53
  • Thanks. We have two situations our code has to handle: to be capable to manage all kind of amount of data. Even more than the max rows returned through a batch query (50M), and also we have to split the call to process the records in different contexts. So the finish block has decide the new scope of the recursive call or finish the process. – aclopezffdc Jul 3 '14 at 14:06
2

You'll need to break the recursion by stopping itself from calling itself more than once during a test:

static boolean recursive = false;

public void finish(Database.BatchableContext bc) {
    if(!recursive) {
        recursive = true;
        // Do your stuff here
    }
}

In the "real world", recursive will always be false, because static variables don't extend beyond the current transaction, while in a test method, it would remain set because it's in the same transaction. This should allow your code to operate correctly both in test method and production mode, while still achieving 100% coverage.

  • Well spotted. However, I have successfully been chaining batches recursively in my tests before. A recent piece of code uncovered the error. I'm trying to recreate an end-to-end test with the minimum possible group of data. Is there a limit on the number of chains in a test context? Looks weird, as it has been working before. – aclopezffdc Jul 3 '14 at 14:34
  • I'll have to experiment. When I get a moment I'll look into it. – sfdcfox Jul 3 '14 at 19:57

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.