test class for batch apex

Let us learn to write a test class that covers a batch apex class. Nothing better than learning from a working example.
Here is a test class for a batch apex class that updates account records that are passed through a select query.

Batch apex class

global class BatchProcessAccount implements Database.Batchable<sobject>{
    String query;
    global Database.querylocator start(Database.BatchableContext BC){
        Query = 'Select id,name,AccountNumber,type from account'; 
        return Database.getQueryLocator(query);
    global void execute(Database.BatchableContext BC, List<account> scope){
       List<account> AccountList = new List<account>();
       for(account acc : scope){
           acc.AccountNumber= '8888';
       update AccountList ;
    global void finish(Database.BatchableContext BC){

Test class for above batch apex class

  private class BatchProcessAccount_Test { 
static testMethod void BatchProcessAccount_TestMethod (){
     Profile prof = [select id from profile where name='system Administrator'];
     User usr = new User(alias = 'usr', email='us.name@vmail.com',
                emailencodingkey='UTF-8', lastname='lstname',
                localesidkey='en_US', profileid = prof.Id,
                insert usr;
   Account accRec = new Account(name='testName', Ownerid = usr.id);
   insert accRec ;
   BatchProcessAccount objBatch = new BatchProcessAccount();
   ID batchprocessid = Database.executeBatch(objBatch);


Just create a instance of the batch apex class: BatchProcessAccount objBatch = new BatchProcessAccount();
and then pass the craeted varaible in executebatch method as below:
   ID batchprocessid = Database.executeBatch(objBatch);

No comments:

Post a comment