Is that possible to create and validate the below start method

public class testBatch implements Database.Batchable<SObject>
    public Database.QueryLocator start(Database.BatchableContext batchableContextVar)
        return Database.getQueryLocator('SELECT Id,Name FROM User');             


what i want is to create test class and assert the below

List<Sobject> sObjecList = testBatch.start(BC)//struck here to create BC

Just want to check this is possible.

  • Seems like when it comes to Apex batch, we are limited to integration testing as opposed to unit testing each (code path in each) method individually. I suppose that we could write additional, testable methods in the Class, and write tests against those.... if the risks justify the rewards. Nov 8 '18 at 20:16

Generally, you use Test.startTest() and Test.stopTest() to test batchable classes, like so:

Database.executeBatch(new testBatch());

The only drawback is that we're limited to a single batch using this method, so that's usually why you'll see either a custom query or custom limit:

global Database.QueryLocator start(Database.BatchableContext context) {
    return Database.getQueryLocator(
        [SELECT Id FROM User LIMIT :Test.isRunningTest()?1:50000000]

Some people prefer to pass in a SOQL string variable, but that's just a bad idea. You should prefer inline static query statements when possible.

  • Agree. Bu my question is to create a test class to check the above start method ?
    – bharath
    Dec 17 '16 at 7:29
  • @bharath And the answer is, you don't, if you want to follow the testing design pattern. You should alter your start method as prescribed. If you have more than 200 users, you'll get errors otherwise.
    – sfdcfox
    Dec 17 '16 at 7:32
  • Agree. I want to create testMethod only for start method ?
    – bharath
    Dec 17 '16 at 7:34
  • test method to ensure the query locator returns records
    – bharath
    Dec 17 '16 at 7:34
  • 1
    @bharath The goal of unit tests isn't to test a system feature. When you run a query on user records, values will be returned. That's like trying to assert that 1 + 1 = 2. If it didn't, then there'd be bigger problems to worry about. You should only worry about the logic that can actually fail, such as what the execute method does.
    – sfdcfox
    Dec 17 '16 at 7:36
    private static testMethod void startTest()
         Database.BatchableContext bc;
         accountBatch obj=new accountBatch();
         obj.query = 'Select id from account';
         Database.QueryLocator queryLocator= obj.start(BC);
         Database.QueryLocatorIterator queryIterator =  queryLocator.iterator();

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.