Sub topic 12
Testing asynchronous callouts
This chapter assumes you can write Apex test classes, know how Test.setMock registers an HttpCalloutMock, and have seen the WeatherService and WeatherServiceMock classes from earlier chapters. Here you will test callouts that run in asynchronous Apex, where the code does not run in the same transaction as the caller.
Why async callouts need care
Many callouts cannot run in the transaction that started them. For example, a trigger cannot make a callout directly after it changes records. A common fix is to move the callout into asynchronous Apex. Two common options are:
- A
@future(callout=true)method. - A
Queueableclass that also implementsDatabase.AllowsCallouts.
Without Database.AllowsCallouts, a Queueable job fails at runtime if it makes a callout. Without callout=true, a future method fails the same way.
In a test, asynchronous work does not run when you enqueue it. It is held until Test.stopTest() is called. At that point the platform runs it synchronously, and it uses the mock you registered.
The test pattern
The order of calls matters:
- Call
Test.setMockfirst, before the asynchronous code is started. - Call
Test.startTest(). - Enqueue the job or call the future method.
- Call
Test.stopTest(), which runs the job and finishes the callout. - Assert on the results.
public class WeatherSyncJob implements Queueable, Database.AllowsCallouts {
private String city;
public WeatherSyncJob(String city) {
this.city = city;
}
public void execute(QueueableContext ctx) {
String condition = WeatherService.getCondition(city);
System.debug('Condition: ' + condition);
}
}
@IsTest
private class WeatherSyncJobTest {
@IsTest
static void runsCalloutInQueueable() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Rain"}'));
Test.startTest();
System.enqueueJob(new WeatherSyncJob('Oslo'));
Test.stopTest();
Assert.isTrue(true, 'Job ran to completion without a callout error');
}
}If the job made a real callout, or if no mock were registered, the test would fail with an error saying that methods defined as TestMethod do not support web service callouts.
Making the test check something
The assertion in the example above is weak. It only proves that nothing threw an exception. A stronger test checks a visible effect of the job, such as a field that the job saves. Debug output is not something a test can read.
For example, if the job wrote the condition to a record, you would query that record after Test.stopTest() and assert on the saved value. The query must come after Test.stopTest(). Before that point the job has not run, so the data has not changed.
@IsTest
static void failedCalloutIsVisible() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(500, '{"error":"boom"}'));
Test.startTest();
System.enqueueJob(new WeatherSyncJob('Oslo'));
Test.stopTest();
List<AsyncApexJob> jobs = [
SELECT Status, NumberOfErrors
FROM AsyncApexJob
WHERE ApexClass.Name = 'WeatherSyncJob'
];
Assert.areEqual(1, jobs.size(), 'One job should have been queued');
}This test looks at AsyncApexJob, the platform record for each asynchronous job. It confirms that the job ran, but it does not prove the job reported the error. In real code, have the job catch the exception and write the failure somewhere you can query, then assert on that.
Future methods
A future method follows the same pattern. Register the mock, then call the method between Test.startTest() and Test.stopTest().
public class WeatherFuture {
@future(callout=true)
public static void fetch(String city) {
WeatherService.getCondition(city);
}
}
@IsTest
private class WeatherFutureTest {
@IsTest
static void futureMethodUsesMock() {
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Snow"}'));
Test.startTest();
WeatherFuture.fetch('Oslo');
Test.stopTest();
Assert.isTrue(true, 'Future method ran without a callout error');
}
}Common mistakes
- Reading results before
Test.stopTest(). The job has not run yet. - Forgetting
Database.AllowsCalloutsorcallout=true. The code fails at runtime, even though it compiles. - Registering the mock after
Test.startTest(). Set it first, so it is in place when the job runs.
Exercise
A test enqueues a Queueable job that makes a callout, then queries a record the job should update. The query returns the old value. What is the most likely cause, and how do you fix it?
Show answer
The query runs before the job has executed, because queued jobs only run when Test.stopTest() is called. Move the query to after Test.stopTest(), and make sure Test.setMock was called before the job was enqueued.