Tag Archives: Batch Apex

Test Class for Batch Apex in Salesforce

Batch Class:

global class BatchAccount implements Database.Batchable<sObject> 
{
    global Database.QueryLocator start(Database.BatchableContext BC) {
		
        return Database.getQueryLocator('SELECT Id,Name FROM Account');
    }
	
    global void execute(Database.BatchableContext BC, List<Account> scope) {
		
        for(Account a : scope)
        {
            a.Name = a.Name + ' Updated';
        }
        update scope;
    }
	
    global void finish(Database.BatchableContext BC) {
		
    }
}

Test Class:

@isTest 
public class BatchAccountTest 
{
    static testMethod void test() 
    {
        List<Account> accList = new List<Account>();
        for(Integer i = 0 ; i < 200; i++)
        {
            Account acc = new Account();
            acc.Name = 'Name' + i;
            accList.add(acc);
        }
        Insert accList;
        
		Test.startTest();
		BatchAccount obj = new BatchAccount();
		DataBase.executeBatch(obj); 
		Test.stopTest();
		
		//Verify accounts updated
		List<Account> accUpdatedList = [SELECT Id, Name FROM Account];
		System.assert(accUpdatedList[0].Name.Contains('Updated'));
    }
}

Undelete Records in Salesforce Using Batch Apex

Sample Code:

global class AccountUndeleteBatchApex implements Database.Batchable<sObject>{
    
    global Database.queryLocator start(Database.BatchableContext bc){
        String query = 'SELECT Id, Name FROM Account WHERE IsDeleted = True ALL ROWS';
        return Database.getQueryLocator(query);
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        List<Account> accList = new List<Account>();
        for(Account s:scope){
            //Write your logic
            accList.add(s);
        }
        Undelete accList;
    }
    
    global void finish(Database.BatchableContext bc){
        
    }
}

Call Batch Apex From Apex Trigger

Batch Apex Class:

global class AccountBatchApex implements database.batchable<sobject>{
    
    global database.querylocator start(database.batchableContext bc){
        String query = 'SELECT Name, AccountNumber, Type From Account';
        return database.getquerylocator(query);
    }
    
    global void execute(database.batchablecontext bd, List<Account> scope){
        for(Account acc: scope){
            //Write your logic
        }  
    }
    
    Public void finish(database.batchableContext bc){ 
    }
}

Apex Trigger:

trigger AccountTrigger on Account (after insert) {
    List<Account> accList = new List<Account>();
    for(account acc : trigger.new){
        if(acc.Type.equals('Customer - Direct')){
            accList.add(acc);
        }
    }
    
    if(accList.size() > 0){
        AccountBatchApex objBatch = new AccountBatchApex();
        Database.executebatch(objBatch,200);
    }
}