1

I had an issue in my batch class, it was picking the same data to process when it is already run for the same earlier.

If the data is processed once, that batch should not pick that data again in the query in the start() method. Fixed this with a flag in the table and filtering out in start() method on the basis of this flag.

I am trying to check if the fix is working using the unit test class with test case having a call like this.

Database.executeBatch(new MyBatch());
Database.executeBatch(new MyBatch());

But the both instances start simantaneously and picking the data in the start method. I need to run them sequentially. I have tried adding loop in these two statements which have time delay with something like this:

Database.executeBatch(new MyBatch());
Integer start = System.Now().millisecond();
while(System.Now().millisecond()< start+10){ 
}

Database.executeBatch(new MyBatch());

But both calls were happening after the completion of the loop. How to run them one after completion of another?

2 Answers 2

1

Running of async apex like Batch apex is different in Test class.

In normal scenario, batch class runs when resources are available. But in test class, batch class executes after Test.stopTest();,

So, you can do something like this

Test.startTest();
Database.executeBatch(new MyBatch());
Test.stopTest(); // here above batch instance will execute
// System.assert for above batch run
Database.executeBatch(new MyBatch());
// unfortunately you cannot have assert statement for 2nd batch run

Since you cannot assert the second batch run, I would recommend below approach.

As you just need to write test class to check if batch is getting correct records, you can try below

// insert 4 records - 2 records with flag true and 2 records with flag false
// query records and assert above
Test.startTest();
Database.executeBatch(new MyBatch());
Test.stopTest(); // here above batch instance will execute
// query records and assert that all 4 records have flag true
1

To achieve this I broke down the calls and did something like this:

MyBatch myBatchObject = new MyBatch();
List<SObject> sObjectList = (List<SObject>)myBatchObject.start(null);
myBatchObject.execute(null, sObjectList);
myBatchObject.finish(null);

myBatchObject = new MyBatch();
sObjectList = (List<SObject>)myBatchObject.start(null);
if(sObjectList.size() > 0 ){
    System.assert( false, 'Size of sObjectList should not be greater than 0' );
}

You must log in to answer this question.

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