function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Mayank.msMayank.ms 

Apex test scheduler class code coverage

Hi Guys,

Need code coverage for apex scheduler class. I am getting only 47% coverage. Can anyone please give me the test class for more than 75% code coverage. 

Batchable Class:
global class TrialExpiredAlertTask implements Database.Batchable<sObject>
{
    global Database.QueryLocator start(Database.BatchableContext BC)
    {
       String query = 'SELECT Id,ownerId,Accounting_Platform__c,StageName FROM opportunity WHERE CloseDate =NEXT_N_DAYS:1 and StageName=\'Trial\' and Accounting_Platform__c IN (\'QuickBooks Enterprise (US)\',\'QuickBooks POS (US)\')';
        
        return Database.getQueryLocator(query);
    }
    global void execute(Database.BatchableContext BC, List<Opportunity> scope)
    { 	
        for(opportunity o : scope){ 
            Task t = new Task();
            t.Subject = 'Trial will expired after one day';
            t.Status = 'Open';
            t.ActivityDate= date.today();   
            t.Priority = 'High';
            t.Type= 'Call';
            t.Description = 'Please call to customer. Trial will expired by tomorrow.';
            t.WhatId =o.Id;
            t.ownerId = o.ownerId;
            insert t;        
        }
        
    }
    global void finish(Database.BatchableContext BC)
    {
        Messaging.SingleEmailMessage mail = new Messaging.SingleEmailMessage();
 
        mail.setToAddresses(new String[] {'kamrantest@gmail.com'});
        mail.setReplyTo('kamrantest@gmail.com');
        mail.setSenderDisplayName('Trial Expired Task alert Batch Processing');
        mail.setSubject('Trial Expired Task alert Batch Process Completed');
        mail.setPlainTextBody('Batch Process has completed');
 
        Messaging.sendEmail(new Messaging.SingleEmailMessage[] { mail });
    }
}
Code Coverage: 

User-added image

Test Class:
@isTest
public class TestScheduleTaskExpirationTaskAlert {

     public static testMethod void TestScheduleTaskExpirationTaskAlertTest()
    { Test.startTest();
        List<Opportunity> oplist = new List<Opportunity>{};
        SchedulableContext SC3;
       
        Account a1 = new Account(Name = 'TestScheduleTaskExpirationTaskAlert');
        insert a1;

        Opportunity opp1 = new Opportunity (Name='TestScheduleTaskExpirationTaskAlert',CloseDate = date.today(), Accountid = a1.id,stageName = 'Trial');
        oplist.add(opp1);
     
        ScheduleTaskExpirationTaskAlert wsch3 = new ScheduleTaskExpirationTaskAlert();
        wsch3.execute(SC3);
        string schedule = '0 5 1-23 * * ?';
     	system.schedule('Process Trans 123', schedule, wsch3);
        
    }

    public static testMethod void testBatchClass()
    {   Test.startTest();
        Database.BatchableContext BC;
       
        TrialExpiredAlertTask b = new TrialExpiredAlertTask();
        ID myBatchJobIDTask = database.executebatch(b);
        Test.stopTest();
    }

}

 
Best Answer chosen by Mayank.ms
James LoghryJames Loghry
The query in the batch class needs to operate over a collection of records.  The execute method never gets called if the query returns an empty result set.  Your test method needs to insert the Opportunity record (you add it to a list of opportunities, but never call the insert opertion).  Add the following to line 14, after oplist.add(opp1);
 
insert oplist;

Additionally, you should also create the mock Opportunity data in your testBatchClass method too.
 

All Answers

James LoghryJames Loghry
The query in the batch class needs to operate over a collection of records.  The execute method never gets called if the query returns an empty result set.  Your test method needs to insert the Opportunity record (you add it to a list of opportunities, but never call the insert opertion).  Add the following to line 14, after oplist.add(opp1);
 
insert oplist;

Additionally, you should also create the mock Opportunity data in your testBatchClass method too.
 
This was selected as the best answer
Mayank.msMayank.ms
Hi James,

Thanks a lot for the reply. Now getting 100% code coverage. 
@isTest
public class TestScheduleTaskExpirationTaskAlert {

     public static testMethod void TestScheduleTaskExpirationTaskAlertTest()
    { Test.startTest();
        List<Opportunity> oplist = new List<Opportunity>{};
        SchedulableContext SC3;
       
        Account a1 = new Account(Name = 'TestScheduleTaskExpirationTaskAlert');
        insert a1;

        Opportunity opp1 = new Opportunity (Name='TestScheduleTaskExpirationTaskAlert',CloseDate = Date.today().addDays(+1), Accountid = a1.id,stageName = 'Trial',Accounting_Platform__c='QuickBooks Enterprise (US)');
        oplist.add(opp1);
     	insert oplist;
     
        ScheduleTaskExpirationTaskAlert wsch3 = new ScheduleTaskExpirationTaskAlert();
        wsch3.execute(SC3);
        string schedule = '0 5 1-23 * * ?';
     	system.schedule('Process Trans 123', schedule, wsch3);
        
    }

    public static testMethod void testBatchClass()
    {   Test.startTest();
        Database.BatchableContext BC;
        TrialExpiredAlertTask b = new TrialExpiredAlertTask();
        ID myBatchJobIDTask = database.executebatch(b);
        Test.stopTest();
    }

}