You need to sign in to do that
Don't have an account?
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:

Test Class:
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:
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(); } }
Additionally, you should also create the mock Opportunity data in your testBatchClass method too.
All Answers
Additionally, you should also create the mock Opportunity data in your testBatchClass method too.
Thanks a lot for the reply. Now getting 100% code coverage.