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';
           AccountList.add(acc);
       }
       update AccountList ;
    }
  
    global void finish(Database.BatchableContext BC){
    }

}
Test class for above batch apex class

@isTest
  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',
                timezonesidkey='America/Los_Angeles',
                languagelocalekey='en_US',
                localesidkey='en_US', profileid = prof.Id,
                username='testuser128@testorg.com');
                insert usr;
   Account accRec = new Account(name='testName', Ownerid = usr.id);
   insert accRec ;
   Test.StartTest();
   BatchProcessAccount objBatch = new BatchProcessAccount();
   ID batchprocessid = Database.executeBatch(objBatch);
   Test.StopTest();
  }

}


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