1

I'm writing a Test class for a method for start function of batch Class

start(Database.BatchableContext BC)

but I don't know what I have to pass as parameter, because start(new Database.BatchableContext()); doesn't work.

How can I test it?

3

As Patlatus suggests, you can sidestep the problem by kicking off the batch and so allowing the platform to supply the Database.BatchableContext. Note that you will need to make sure that the execute method only ever gets called once (by adding the right amount of data in relation to the scope size you supply in the test) as otherwise the test will fail. You also need a Test.stopTest() in the test method as that call causes the batchable to be run synchronously within the test.

So some sequence like this is needed in your test method:

// Do data setup
Integer scopeSize = ...;
Database.executeBatch(new YourBatchable(), scopeSize);
Test.stopTest();

(If you need to call your batchable's methods directly and your batchable does not reference the Database.BatchableContext, you can just supply null instead of an object instance.)

2

You need to write a method

static testMethod void testBatch() {
    Database.executeBatch( new BatchName() );
}
1

If you wanted to test the batch's methods individually without passing null as the context, you can also implement Database.BatchableContext in a class:

public class BatchableContextImplementation implements Database.BatchableContext
{
    private ID childJob, job;
    public BatchableContextImplementation(ID job, ID childJob)
    {
        this.job = job;
        this.childJob = childJob;
    }
    public ID getChildJobID()
    {
        return childJob;
    }
    public ID getJobID()
    {
        return job;
    }
}

Test Method:

@isTest
public class batchtest implements Database.Batchable<integer>
{
    public List<integer> start(Database.BatchableContext context)
    {
        System.debug(context.getJobID());
        return new List<integer>{1, 2, 3, 4, 5};
    }
    public void execute(Database.BatchableContext context, List<integer> scope)
    {
        System.debug(context.getChildJobID());
    }
    public void finish(Database.BatchableContext context)
    {

    }
    public static testmethod void test()
    {
        batchtest testObj = new batchtest();
        BatchableContextImplementation context = 
            new BatchableContextImplementation(UserInfo.getUserID(), UserInfo.getUserID());
        List<Integer> scope = testObj.start(context);
        testObj.execute(context, scope);
        testObj.finish(context);
    }
}

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.