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';
           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);

 

2 comments:

JIMY said...

thank you....

Server and storage

Server and Storage Solutions

nick jones said...

thanks for sharing..
Wireless Access Points

Post a Comment

 
| ,