+ Start a Discussion
Vasavi VajinepalliVasavi Vajinepalli 

Please help me in writing a test class for batch apex with size 1

Hi,

please help me in writing the test class for the below batch apex:
global class scheduleResendFileToAPI implements Schedulable{

    global void execute(SchedulableContext sc) {
        resendFileToAPI d = new resendFileToAPI();
        database.executebatch(d,1);
    } 
}

Test class which i tried:
@isTest(SeeAllData=true)
private class TestScheduleResendFile

    static testMethod void TestScheduleResendFile()
    { 
        scheduleResendFileToAPI res = new scheduleResendFileToAPI();
        String sch = '0 0 * * * ?'; 
        test.startTest();
        system.schedule('testResendFile', sch, res);        
        test.stopTest();
    }
}

when i try to run this test, am getting below exception:
"System.UnexpectedException: No more than one executeBatch can be called from within a testmethod.  Please make sure the iterable returned from your start method matches the batch size, resulting in one executeBatch invocation."

Thanks,
vasavi 
 
James LoghryJames Loghry
  1. Remove the SeeAllData=true annotation.  This tells the query in your batch class to pick up all the existing data in your organization, and is generally a bad practice.
  2. Create mock records in your test class instead of relying on the existing data.  
  3. Profit.
Amit Chaudhary 8Amit Chaudhary 8
Please check below post. I hope that will help u
https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US (https://help.salesforce.com/apex/HTViewSolution?id=000176562&language=en_US)

>> Try to pass the less than 200 records in test class.

>> What you have to consider is using the Test.isRunningTest to bypass the code starting the second job in this context. Meaning that you will have to test your second batch job in a separate test to get coverage and assert behaviour. In doing so you will obvsiouly have to reproduce manually in the test code the state in the database the second job expects. Not ideal, but should work.
 
The following is an example of the change to avoid the second batch job being executed during test execution.

 
public void finish(Database.BatchableContext)
{
    if(!Test.isRunningTest)
         Database.executeBatch(new MySecondBatchJob));
}


>> Enclose the executeBatch in Test.startTest() and Test.stopTest()

>> always try to use @SeeAllData=false


Please let us know if this will help  you

Thanks
Amit Chaudhary