+ Start a Discussion
Sanjat Samal 8Sanjat Samal 8 

Test Class For Schedule Class

How to write a test class for schedule apex class? For Below Code.
global class ClearHistoricalAccountCaseScheduler implements Schedulable
{
    global void execute(SchedulableContext SC) 
    {    
        System.debug('ClearHistoricalAccountCaseScheduler Start...');        
        
        List<Account> accountList = [Select Case_Life__c From Account Where Case_Life__c != '3 Years' and Case_Life__c != '2 Years'];
        Integer accountIndex = 0;
        if(accountList.size() > accountIndex)
        {
            ClearHistoricalAccountCaseBatch batchDelete = new ClearHistoricalAccountCaseBatch();
            batchDelete.accountList = accountList;
            batchDelete.accountIndex = accountIndex;
            ID batchProcessId = Database.executeBatch(batchDelete, 200);
            System.debug('Returned Batch Process ID: ' + batchProcessId);           
        }
        
        System.debug('ClearHistoricalAccountCaseScheduler Stop...'); 
    } 
}

Thanks
Steven NsubugaSteven Nsubuga
@isTest
private class ClearHistoricalAccountCaseSchedulerTest {

    static testmethod void schedulerTest() {
        String CRON_EXP = '0 0 0 15 3 ? *';
        
        // Create your test data
        Account acct = new Account();
        acct.name= 'test';
		acct.Case_Life__c = '5 years';
        insert acct;
        
        Test.startTest();

            String jobId = System.schedule('HistoricalAccountCaseScheduler',  CRON_EXP, new ClearHistoricalAccountCaseScheduler());
            CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered, NextFireTime FROM CronTrigger WHERE id = :jobId];
            System.assertEquals(CRON_EXP, ct.CronExpression);
            System.assertEquals(0, ct.TimesTriggered);

        Test.stopTest();
    }
}

 
Niraj Kr SinghNiraj Kr Singh