The issue here is that the instance of VisitReminder constructed in your test is not the same instance that is instantiated by the platform Scheduler within the start and stop test scope. So your asserts are failing since the instance in the vr variable is never actually the executed instance.
The instance created by the Scheduler is created from a de-serialised copy of the one originally given to System.schedule by your test code. Unfortunately there is no way to access this instance or its state, its more than likely it is executed on another thread in the server and then destroyed.
The only state the test and the scheduled class share is the database and static variables. Added to the complication is that your only output of this is a set of emails, which do not get executed in a test anyway. Its interesting that the Salesforce example includes asserts in the schedule class.
So I see a few options...
- Place the Asserts in the Schedule Class. Its interesting that the Salesfore example places asserts in the schedule class. So I thought I'd try it. Indeed this works, and of course you can condition the execution of the System.assert calls around a Test.isRunningTest() check. This is probably your cheapest option, but is also a little ugly to see in production code and not in test code.
- Assert Callbacks. Inspired by KeithC's comment on the other answer and the above observation, I've developed a generic solution to allow you to express the asserts in your test code, yet have them invoked during the execution of the scheduled job with the correct state available. See below for more details on this approach.
- Use of Static Variables. You can create a static @TestVisible variable in your VisitReminder class, e.g. testReminders and testSendResults, then in the last statements of the execute assign these from the instance versions. Your test will be able to see these via VisitReminder.testReminders etc. Personally I feel this is leveraging an implementation detail of the platform, that said I've seen it used elsewhere so likely now one of those approaches that will be here to stay.
- Use of a Reminder History Object.. You may want to consider that having a history of what reminders have been sent for future reference is a good feature to give to your users. Thus if so a new object will also help with your testing, as records emitted by the scheduled class can readily be asserted via SOQL in the test code.
- Email.setSaveAsActivity. You may in fact want to look at using setSaveAsActivity as this saves email activity to the target object of the email (if you have an appropriate one). This might in fact be a good feature anyway for you to review when reminders where sent historically.
Some of these solutions require changes to your schedule class solely for the benefit of your test, you can condition such code paths around a Test.isRunningTest() condition.
NOTE: Use of the 'global' modifier is optional these days (yet the Salesforce examples still include it). If your packaging this code this will be important to you, as it bakes in the class name and signature to the package. If your not packaging its not that big a deal. Eitherway you can use 'public' if you want.
An AssertCallback Solution
As per my summary of options above, this is inspired by KeithC's comment about using a logging approach to capture information to later assert, combined with an observation that asserts don't have to be executed in the immediate code path of the executing test.
First the usage, here is my Scheduled job.
public with sharing class MyScheduledWork implements Schedulable {
@TestVisible
private String message;
public void execute(SchedulableContext SC)
{
message = 'Goodbye X';
AssertCallback.assert(MyScheduledWork.class, 'execute', this);
}
}
And now my test...
@IsTest
private with sharing class MyScheduledWorkTest {
@IsTest
private static void testSchedule()
{
// Register assert callback
AssertCallback.registerCallback(MyScheduledWork.class, new AssertMyScheduleWork());
// Run the scheduled job
MyScheduledWork testSchedule = new MyScheduledWork();
testSchedule.message = 'Hello';
Test.startTest();
System.schedule('Test', '0 0 19 * * ?', testSchedule);
Test.stopTest();
}
public class AssertMyScheduleWork implements AssertCallback.IAssertCallback
{
public void assert(String location, Object state)
{
// Assert callback from MyScheduledWork?
if(state instanceof MyScheduledWork)
{
// State to assert
MyScheduledWork myScheduledWork = (MyScheduledWork) state;
// Assert the state of the scheduled job
System.assertEquals('Goodbye', myScheduledWork.message);
}
}
}
}
There is a deliberate bug in the above to test the assertion fires and gives a meaningful stack trace.
Summary: As you can see this solution requires some instrumentation of the code your testing, which could in fact be used regardless of batch/schedule or not (a poormans Mockito). So yes it does have the overhead of calling a method in your code, which if you where really concerned about statements could be conditioned around Test.isTestRunning(). Though the AssertCallback.assert method does do this also. The main thing though is it has allowed you to assert anything you want, when you want.
Finally you can find the source code to the AssertCallback class here.
Hope this helps!
Suppose you have a Schedulable class and when it runs, the behavior of the execute()
method doesn’t match what you expect. It looks like there’s memory of previous execute()
s
Here is a specific example that distills the issue
public class MySchedulable implements Schedulable {
Account[] accts = new List<Account>();
public void execute(SchedulableContext sc) {
accts.addAll([select id, name from Account where YTD_Total__c < 1000.0]);
// do something interesting with this
}
You run the job weekly. You observe on week n, where n > 1, that Accounts are being processed that currently don’t have a YTD_Total__c
< 1000. Accounts with YTD_Total__c
> 1000 are being processed (?!?)
Explanation
- When the job is scheduled, the class constructor is called (here, the implicit constructor) and the object variable
accts
is initialized empty.
- On week 1, when execute() is called, the accounts with
YTD_Total__c
< 1000 as of week 1 are added to list accts
.
- On week 2, when execute() is called, the accounts with
YTD_Total__c
< 1000 as of week 2 are added to list accts
.
Note that the class constructor is not reinvoked for each execute(). Hence, the accts
list grows and grows. accts
is never cleared.
Solution
Reinitialize all object variables within the execute().
public class MySchedulable implements Schedulable {
public void execute(SchedulableContext sc) {
Account[] accts = new List<Account>();
accts.addAll([select id, name from Account where YTD_Total__c < 1000.0]);
// do something interesting with this
}
Best Answer
Yes, you can call batchable classes from schedulable classes. This is a very common use case.
As for testing you'll want to test them separately. Test methods for my schedulable classes that invoke a batchable class just verify that the batchable class is queued after the scheduled class has executed. I then have a separate test methods for my batch class that is queued for the test directly rather than through the schedulable class.
The reason behind this is the Test.stopTest() method only clears out queues (future, batch, scheduled) once. So you can have multiple future and batch calls run at that point, but if those cause any further queuing of processes they aren't run. Currently there isn't a way to flush the queues twice, just need to test them separately, which personnally I feel is a better and clearer testing scheme since it separates the various roles of each class better.