1

I'm attempting to test my batch job where I'm querying Users based on JobGrade and creating a custom record for each. For some reason, my test function keeps using org data instead of test data that I'm creating. I'm not using SeeAllData=True so I'm a little confused on why this is happening.

Then I keep getting the error no more than one executebatch can be called from within a test method

I attempted to delete all the User records but I can't use the delete operation on User objects. Any idea how to approach this issue?

1

When dealing with Setup data in Unit Tests, you typically have to find a way to "inject" a fake query in order to limit the number of records the batch will process. That typically looks like this:

public class SomeBatch implements Database.Batchable<SObject> {
  @TestVisible String query = 'SELECT Id FROM User WHERE ...';
  public Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator(query);
  }
  ...

Which you would then update in your unit test:

SomeBatch b = new SomeBatch();
b.query = 'SELECT Id FROM User WHERE ... LIMIT 200';
Test.startTest();
Database.executeBatch(b);
Test.stopTest();
// verify results

There are other methods you can use, as well, such as using the Stub API, which allows you to use dependency injection. However, in most cases, that's overkill, but if you had a standard framework for this, it would allow you to build compile-safe code, but there's a minimum overhead to make this work that wouldn't be worth it for a one-off situation.

1

The users are available in your test because the User object is a setup object. Some other objects are included on that list. You can see some of those in the Isolation of Test Data from Organization Data in Unit Tests documentation.

The "more than one executebatch" error can be caused by the fact that your method is trying to run for multiple users. Assuming your batch class will process 200 records at once, for example, then your test should not handle more than 200 records. Otherwise it will try to run the code exactly as a batch (which means running twice or more, attempting to process all the 200+ records).

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.