+ Start a Discussion
CBNCBN 

How to write test class for batch apex and schedule apex

.....................Batch apex.............................

global class BatchUpdateAccountField implements Database.Batchable <SObject>{
global Database.QueryLocator start (Database.BatchableContext bc)
{
    return Database.getQueryLocator('SELECT name from Account');
}
   global void execute(Database.BatchableContext bc, List<Account> acList)
   {
       for(Account ac :acList)
       {
          ac.name = ac.name + ' Testing';
           
       }
       
       update acList;
   }
    
    global void finish(Database.BatchableContext bc)
    {
        System.debug('>>>Finish');
    }
    
}



...................Schedule apex..............

global class ScheduleBatchAccFieldUpdate implements Schedulable {
    global void execute(SchedulableContext sc)
    {
        BatchUpdateAccountField ba =new BatchUpdateAccountField();
        Database.executeBatch(ba);
    }

}
Best Answer chosen by CBN
Raj VakatiRaj Vakati
Use this
@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 testBatch() {        
        Test.startTest();
        BatchUpdateAccountField   uca = new BatchUpdateAccountField  ();
        Id batchId = Database.executeBatch(uca);
        Test.stopTest();
       
    }
    
	
	 static testmethod void testSch() {        
       Test.startTest();
            String CRON_EXP = '0 0 0 1 1 ? 2025';  
			String jobId = System.schedule('testScheduledApex', CRON_EXP, new ScheduleBatchAccFieldUpdate() );
            Test.stopTest();
       
    }
}