0

Is there any way to mock a batch class for unit testing and predefine the scope passed to execute method? I am using a selector class method for Database.getQueryLocator at start method.

public class someBatchClass implements Database.Batchable<sObject>{

    public Database.QueryLocator start(Database.BatchableContext BC){
       return new SomeSelectorClass().someMethod();
    }
    
    public void execute(Database.BatchableContext BC, List<sObject> scope){
       for(Sobject s : scope){
           doSomething;
       }
       update scope;
    }

    public void finish(Database.BatchableContext BC){

    }
}

1 Answer 1

2

You are specifically forbidden from mocking batchable class, as noted in the documentation:

You can’t mock the following Apex elements.

  • Static methods (including future methods)
  • Private methods
  • Properties (getters and setters)
  • Triggers
  • Inner classes
  • System types
  • Classes that implement the Batchable interface
  • Classes that have only private constructors

That said, you can call the methods directly, as it is a normal class. This is typically I might "mock" the batchable:

someBatchClass theBatch = new someBatchClass();
sObject[] records = generateRecords(); // do as you will
theBatch.execute(null, records); // And with scope

Note that this has the disadvantage of having only the usual synchronous governor limits (10 seconds CPU, 6MB heap) instead of the more generous asynchronous limits. That said, I usually use small batches for testing logic, and larger batches as a "canary in the coalmine" test for slow code.

1
  • Thank you very much for the detailed explanations! I appreciate it.
    – selman
    Commented Mar 6 at 14:25

You must log in to answer this question.

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