+ Start a Discussion
CBNCBN 

How to write test class for batch apex for following code

global class Batch_UpdateAcc implements Database.Batchable<sObject>{
    
    List <Account> mapAccount = new List <Account> ();
    
    global Database.QueryLocator start(Database.BatchableContext bc){
        return Database.getQueryLocator('SELECT ID, BillingCountry, ShippingCountry FROM Account');
    }
    
    global void execute(Database.BatchableContext bc, List<Account> scope){
        for(Account acc : scope){
            if(acc.BillingCountry=='UK'){
                acc.BillingCountry = 'United Kingdom';
            }
            if(acc.ShippingCountry=='UK'){
                acc.ShippingCountry = 'United Kingdom';
            }
            if(acc.BillingCountry=='USA'){
                acc.BillingCountry = 'United States';
            }
             if(acc.ShippingCountry=='USA'){
                acc.ShippingCountry = 'United States';
            }
            mapAccount.add(acc);
        }
        UPDATE mapAccount;        
    }
    
    global void finish(Database.BatchableContext bc){
        
    }     
}
Best Answer chosen by CBN
Raj VakatiRaj Vakati
try this code
 
@isTest
private class UpdateContactAddressesTest {
    @testSetup 
    static void setup() {
        List<Account> accounts = new List<Account>();
            accounts.add(new Account(name='Account 1', 
                billingcity='New York', billingcountry='UK'));
				
				 accounts.add(new Account(name='Account 1', 
                billingcity='New York', billingcountry='USA'));
				
				 accounts.add(new Account(name='Account 1', 
                billingcity='New York', ShippingCountry='USA'));
				
				 accounts.add(new Account(name='Account 1', 
                billingcity='New York', ShippingCountry='UK'));
				
				
				
				
        insert accounts;
     }
    static testmethod void test() {        
        Test.startTest();
        Batch_UpdateAcc  uca = new Batch_UpdateAcc ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
       
    }
    
}