1

I'm writing test methods for my scheduled apex classes and I find the test methods are almost the same. How can I write a method and pass the scheduled apex class name as parameter so I can reuse the method?

@isTest static void test_Method1() {
    Test.startTest();
    String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, new Method1Scheduler());
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE id = :jobId];
    System.assertEquals(CRON_EXP,ct.CronExpression);
    System.assertEquals(0, ct.TimesTriggered);
    System.assertEquals('2022-03-15 00:00:00',String.valueOf(ct.NextFireTime));
    Test.stopTest();
}


@isTest static void test_Method2() {
    Test.startTest();
    String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, new Method2Scheduler());
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE id = :jobId];
    System.assertEquals(CRON_EXP,ct.CronExpression);
    System.assertEquals(0, ct.TimesTriggered);
    System.assertEquals('2022-03-15 00:00:00',String.valueOf(ct.NextFireTime));
    Test.stopTest();
}


@isTest static void test_Method3() {
    Test.startTest();
    String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, new Method3Scheduler());
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE id = :jobId];
    System.assertEquals(CRON_EXP,ct.CronExpression);
    System.assertEquals(0, ct.TimesTriggered);
    System.assertEquals('2022-03-15 00:00:00',String.valueOf(ct.NextFireTime));
    Test.stopTest();
}


@isTest static void test_Method4() {
    Test.startTest();
    String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, new Method4Scheduler());
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE id = :jobId];
    System.assertEquals(CRON_EXP,ct.CronExpression);
    System.assertEquals(0, ct.TimesTriggered);
    System.assertEquals('2022-03-15 00:00:00',String.valueOf(ct.NextFireTime));
    Test.stopTest();
}

1 Answer 1

2

Try this? Haven't tested but should work:

static void test_template(Schedulable s, String CRON_EXP, String EXP_RESULT) {
    Test.startTest();
    String jobId = System.schedule('ScheduleApexClassTest', CRON_EXP, s);
    CronTrigger ct = [SELECT Id, CronExpression, TimesTriggered,NextFireTime FROM CronTrigger WHERE id = :jobId];
    System.assertEquals(CRON_EXP,ct.CronExpression);
    System.assertEquals(0, ct.TimesTriggered);
    System.assertEquals(EXP_RESULT,String.valueOf(ct.NextFireTime));
    Test.stopTest();
}

@isTest static void test_Method1() {
    Schedulable s = new Method1Scheduler();
    test_template(s, '0 0 0 3 9 ? 2022', '2022-03-15 00:00:00');
}

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .