Wednesday, September 3, 2014

How to writeTest class for batch apex in salesforce?

How to write Test class for batch apex in salesforce?

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 clas
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='',
                emailencodingkey='UTF-8', lastname='lstname',
                localesidkey='en_US', profileid = prof.Id,
                insert usr;
   Account accRec = new Account(name='testName', Ownerid =;
   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);



Post a Comment

| ,