+ Start a Discussion
Sid LightningSid Lightning 

Need help in writting Test class for batc Class

Hi,

I need help in writting test class for below written batch class.

Can anyone help please?

global class UpdateCurrentMonth implements Database.Batchable<sObject>,Schedulable, Database.stateful
{

  global void execute(SchedulableContext sc)
    {
        
    }


   global Database.queryLocator start(Database.BatchableContext BC )
   {
        String str = 'SELECT Id, Start_Date__c,End_Date__c,Current_Month__c FROM Business_Re_development_Target__c';
        return Database.getQueryLocator(str);
        
   }
    
    global void execute(Database.BatchableContext BC, List<Business_Re_development_Target__c> BRTToProcess)
     {
     List<Business_Re_development_Target__c> BRTList = new List<Business_Re_development_Target__c>();
       for(Business_Re_development_Target__c BRTObj : BRTToProcess){
       
       If(Date.Today().Year()  == BRTObj.End_Date__c.Year()){
      
       If(Date.Today().Month()  > BRTObj.End_Date__c.month())
       {
       
               BRTObj.Current_Month__c = False;
            BRTList.add(BRTObj);
            }            
            }
        
        else
         
       If(Date.Today().Year() > BRTObj.End_Date__c.Year()){
      
       If(Date.Today().Month()  < BRTObj.End_Date__c.month())
       {
       
               BRTObj.Current_Month__c = False;
            BRTList.add(BRTObj);
            }            
            }
               
            
          }
        update BRTList;
        }
   global void finish(Database.BatchableContext BC)
    {
   system.debug('finish');     
    }    
}
    
     

    
Maharajan CMaharajan C
Hi,

Please try the below test class:
 
@istest
public class UpdateCurrentMonthTest {
    static testmethod void testMyController(){
        
        List<Business_Re_development_Target__c> brdtList = new List<Business_Re_development_Target__c>();
		Integer lastyear = Date.today().year() - 1;
		Date dToday = Date.today();

        for(Integer i = 0 ; i < 12; i++)
        {
            Business_Re_development_Target__c rec = new Business_Re_development_Target__c();
            rec.Start_Date__c = Date.newInstance(dToday.year(), i + 1, 1);
			rec.End_Date__c = Date.newInstance(dToday.year(), i+1,25);
            brdtList.add(rec);
        }
		
		for(Integer i = 0 ; i < 12; i++)
        {
            Business_Re_development_Target__c rec1 = new Business_Re_development_Target__c();
            rec1.Start_Date__c = Date.newInstance(lastyear, i + 1, 1);
			rec1.End_Date__c =  Date.newInstance(lastyear, i+1,25);
            brdtList.add(rec1);
        }
        
		if(!brdtList.isEmpty())
		insert brdtList;
		
        Test.StartTest();
        UpdateCurrentMonth obj = new UpdateCurrentMonth();
        DataBase.executeBatch(obj);
        Test.StopTest();
		
		// Add some assert statements here to verify the results
    }
}

Thanks,
Maharajan.C