function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Rocks_SFDCRocks_SFDC 

How to write test class for Batch Class

Hello Everyone,

 

I have a batch class which will delete the Accounts having Duplicate_Id__c !=null according to our shedule time. Please let me know how we can write the test class for it.

 

Code:

 

global class DeleteAccount implements Database.Batchable<SObject>
{

   Public String Query='Select Id, Duplicate_ID__c From Account where Duplicate_ID__c!=null';   
    global  Database.QueryLocator Start(Database.BatchableContext BC)
    {
      return Database.getQueryLocator(query);
    } 
    global void Execute(Database.BatchableContext BC,List<Account> accs)
    {
    try{
      List<Account> ListAcc =new List<Account>();
      for(Account objAcc:accs)
      {
            if(objAcc.Duplicate_ID__c !=null)
            {
                ListAcc.add(objAcc);
            }
 
        }
        if(ListAcc!=null && ListAcc.size()>0)
        list<Database.DeleteResult> sr = Database.delete(ListAcc,false);      
    }catch(Exception e){} 
    }
    global void finish(Database.BatchableContext BC)
    {
    }
    
}

Devender MDevender M
@isTest
private class TestBatch {
static testMethod void TestbatchMethod() {
// mention required for account before insert

Account acc1 = new Account(Duplicate_ID__c = 'xxxxxxxx');
insert acc1;

Account acc2 = new Account(Duplicate_ID__c = 'xxxxxxxx');
insert acc2;


system.Test.startTest();
DeleteAccount b = new DeleteAccount();
database.executeBatch(b);
system.Test.stopTest();
}
}
Yoganand GadekarYoganand Gadekar

A working example is here see if it helps you out:

http://cloudforce4u.blogspot.in/2013/07/test-class-for-batch-apex.html