Batch Apex

Batch Apex can be used to run large jobs that would exceed normal processing limit.
If you have a lot of records to process, Batch Apex is your best solution to do this stuff.

To Write batch apex class you have to implement Database.Batchable interface that consists three methods.
1. start method
2. execute method
3. finish method

Here are the signatures of all three methods in this interface

global class ClassName implements Database.Batchable<sObject> {

    global Database.QueryLocator start(Database.BatchableContext BC) {
        // collect the scope of records or objects to be passed to execute method
    }

    global void execute(Database.BatchableContext bc, List<sObject> scope){
        // process each batch of records
    }

    global void finish(Database.BatchableContext bc){
        // execute any post-processing operations
    }

}


You can understand the working of  Batch Apex by implementing this example which updates Lead Record.

You can do this stuff here---  Batch Apex


Batch Apex Class--

global class LeadProcessor implements Database.Batchable<sObject>{

    global Database.QueryLocator start(Database.BatchableContext BC){
   
        String query = 'select Id,Lastname,LeadSource from Lead';
        return Database.getQueryLocator(query);
    }

    global void execute(Database.BatchableCOntext BC, List<Lead> scope){

        List<Lead> newLead = new List<Lead>();
        for(Lead l: scope){
            if(l.LeadSource == null){
                l.LeadSource = 'Dreamforce';
                newLead.add(l);
            }
        }
        update newLead;
    }

    global void finish(Database.BatchableContext BC){

    }
}

Test Class for above apex class which contain 100% test-coverage--

@isTest
public class LeadProcessorTest{

    public static testMethod void positiveScenario(){
   
        Lead l = new Lead();
        l.LastName = 'Piggy';
        l.Company = 'Dell';
        l.Status = 'Open';
        insert l;
   
        Test.startTest();
           // pass the LeadProcessor Class object as an arguments
        Database.executeBatch(new LeadProcessor());
        Test.stopTest();
 
        List<Lead> leadList = new List<Lead>();
        for(Lead ld : [select Id,LastName,LeadSource from Lead ]){
            if(ld.LeadSource == null){
                ld.LeadSource = 'Hello';
                leadList.add(ld);
            }       
        }
        update leadList;
        System.assertEquals(0,leadList.size());
   }
}

Comments

Popular posts from this blog

Dynamically Add/Delete rows in Visualforce Page

Process Automation Specialist Superbadge

How to show or hide a particular section of Visualforce Page dependent upon picklistfield value