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
TerminusbotTerminusbot 

Test Class for Apex Scheduler that executes a Callout

I am trying to create a class that does nothing more than fire a set of Apex Scheduler classes I have created. Here is the test class I have created to execute them.
 
@isTest(seeAllData=true)
private class TestCronClass {
	
	@isTest static void executeCrons() {
		
		String sch = '0 0 23 * * ?';

		Test.StartTest();
			
			ClientDetlaCron clientCron = new ClientDetlaCron();
			System.schedule('Test Client Cron', sch, clientCron);
			
			PolicyCronBatchQuery policyCron = new PolicyCronBatchQuery(); 
			System.schedule('Test Policy Cron', sch, policyCron);
		

		Test.stopTest();
	

	}
	
	
}

I am getting an error becuase in the Scheduler classes they do nothing more than fire off a Callout to an external system. The test class fails since the class is executing a callout class.

I was thinking about using "if (Test.isRunningTest())" and try and avoid this but wanted to see if anyone has any better design patterns here. 

One of my scheduler classes. The other one is the exact same just calls a different callout.
global class ClientDetlaCron implements Schedulable {
	
	global void execute(SchedulableContext sc) {
		// Fire Soap Request to Sagitta for Changes in Policy Data
		ClientBatchQuery.sendBatchQuery();		
	}
}


I already have a Test Class and MockClass for the Callouts. 

Thanks for you help.
Agustina GarciaAgustina Garcia
Have you tried to create 2 tests? One per schedule job? And include the call inside the Test.startTest / Test.stopTest

I would not advice to go inside that piece of code if you are running a test because you would decrease the test coverage.
Andrew Lewis 20Andrew Lewis 20
In your test class, set the mock for your callout before the startTest() and stopTest() methods. Like this:
 @isTest static void executeCrons() {
05         
06        String sch = '0 0 23 * * ?';
07        Test.setMock(ImplementedCalloutMockName.class, new MockCalloutClassName());
08        Test.StartTest();
09             
10            ClientDetlaCron clientCron = new ClientDetlaCron();
11            System.schedule('Test Client Cron', sch, clientCron);
12             
13            PolicyCronBatchQuery policyCron = new PolicyCronBatchQuery();
14            System.schedule('Test Policy Cron', sch, policyCron);
15         
16 
17        Test.stopTest();
18     
19
20    }

Test.setMock() is not asynchronous, so it doesn't require being tied to Test.startTest() and Test.stopTest(). It'll execute first, create your mock response, and then your asynchronous apex inside your test methods will callout against the mock.