+ Start a Discussion
linda blinda b 

Write test class for Scheduled Apex

Hello, can someone please help me write a test for this class?

global class CaseGenerator implements Schedulable {
    global void execute(SchedulableContext ctx) {
        createInvoiceCase();
    }
    public void createInvoiceCase() {
        List<Case> newCaseList = new List<Case>();
        List<Billing_Unit__c> invoiceCases = [SELECT Id, Contract__c, Name
                                             FROM Billing_Unit__c
                                             WHERE Invoicing_Date__c = TODAY AND
                                             Unlimited__c = TRUE];
        if(invoiceCases != null){
            for(Billing_Unit__c bgut : invoiceCases){
                Case cseobj = new Case(
                    subject='Rechnung erstellen: '+bgut.Name,
                    Contract__c=bgut.Contract__c,
                    Automatically_generated__c=TRUE,
                    Billing_Unit__c=bgut.Id,
                    Status='New');
                 newCaseList.add(cseobj);
            }
            insert newCaseList;
        }
    }
}


This is what I have so far, but I do not think I am going in the right direction:

public class CaseGeneratorTest{
    public static String CRON_EXP '0 0 6 * * *';
    static testMethod void testScheduledJob(){
        List<Case> newCaseList = new List<Case>();
        Test.startTest();
                    invoiceCasesListTest invcs = new List<Case>
                    invcs.Invoicing_date__c = TODAY,
                    invcs.Unlimited__c = TRUE;


...
Best Answer chosen by linda b
PawanKumarPawanKumar
Please try below.

private class CaseGenerator_Test{
    static testmethod void testSchduler() 
    {
        //prepare test data
        Billing_Unit__c billingUnit = new Billing_Unit__c();
        billingUnit.Invoicing_Date__c = DateTime.Now();
        billingUnit.Unlimited__c = TRUE;
        billingUnit.Name = 'Test BU1';
        insert billingUnit;
        //-- END test data
        
        // code coverage
        String CRON_EXP = '0 0 0 15 3 ? *';
        Test.startTest();
        String jobId = System.schedule('CaseGenerator',  CRON_EXP, new CaseGenerator());
        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();
    }
}

Please mark it best if it helps you. Thanks.