+ Start a Discussion
Mahesh K 22Mahesh K 22 

How to write test class for batch apex

global class batchapex implements database.Batchable <sObject>,database.stateful {
    public integer i = 0;
       global database.QueryLocator start(database.BatchableContext bc){
           string query ='select id,First_name__c,Last_Name__c,Phone_No__c from Registration__c' ;
           system.debug('======================>'+query);
        return database.getQueryLocator(query);
    }
    global void execute(database.BatchableContext bc,list<Registration__c> reg){
        list<Registration__c> regupdate = new list<Registration__c>();
        for(Registration__c r:reg){
            r.Phone_No__c='04056' + i;
            r.Last_Name__c='mahesh'+i;
            r.Email__c = 'kmsr1055@gmail.com';
            regupdate.add(r);
            i++;
         }
        update regupdate;
      }
     global void finish(database.BatchableContext bc){
         Messaging.SingleEmailMessage email1= new Messaging.SingleEmailMessage();
       list<string> addemails = new list<string>();
               addemails.add('mahi.k418@gmail.com');
            email1.setToAddresses(addemails);
             email1.setPlainTextBody('this is inserting');
            email1.setSubject('inserting records into database');
            email1.setSenderDisplayName('Mahesh');
        Messaging.sendEmail(new Messaging.SingleEmailMessage [] {email1});
            
        }

}
NagendraNagendra (Salesforce Developers) 
Hi Mahesh k 22,

Please refer to the below link for writing a test class for the batch apex.
http://www.salesforce.com/us/developer/docs/apex_workbook/Content/apex_batch_2.htm

Please let us know if it helps you.

Best Regards,
Nagendra.P