Sub topic 12
Testing with HttpCalloutMock
This chapter assumes you can write Apex test classes, know that Test.startTest() and Test.stopTest() reset governor limits, and have read the earlier chapters on Queueable callouts from triggers.
Why tests need a mock
Apex tests are not allowed to make real HTTP callouts. If your trigger enqueues a job that calls Http.send(), the test fails with System.CalloutException: You have uncommitted work pending or a "Methods defined as TestMethod do not support Web service callouts" error, depending on the path. To fix this, you register a fake response with Test.setMock. The platform then returns that response instead of contacting the endpoint.
A mock is a class that implements the HttpCalloutMock interface. It has one method, respond, which receives the HttpRequest and returns an HttpResponse.
Writing the mock
The test below reuses the AccountSyncJob from earlier in this tutorial.
@IsTest
private class AccountSyncJobTest {
private class MockOk implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void enqueuesAndRunsJobAfterInsert() {
Test.setMock(HttpCalloutMock.class, new MockOk());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Integer completed = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'Queueable' AND ApexClass.Name = 'AccountSyncJob' AND Status = 'Completed'
];
System.assertEquals(1, completed, 'The Queueable job should have run');
}
}What each step does
Test.setMockis called before the code that makes the callout. It applies to every callout in the rest of the test method.Test.startTest()begins a fresh set of governor limits.- The
insertfires the trigger, which callsSystem.enqueueJob. The job is queued but has not run yet. Test.stopTest()forces all queued asynchronous work to finish before the next line runs. Without it, the job would still be waiting and your assertion would see nothing.- The query checks
AsyncApexJobto confirm the job completed.
Common errors
| Symptom | Likely cause |
|---|---|
| `You have uncommitted work pending` or callout not allowed | No `Test.setMock` call, or it was placed after the DML |
| Assertion finds no job or no result | Missing `Test.stopTest()`, so the job never ran |
| `System.CalloutException` about no mock | The mock was set for a different type, such as `WebServiceMock` |
| Only one response is possible | One mock class returns the same reply to every request |
Testing failure paths
A happy-path test proves little. Write a second mock that returns a 500 status so you can check how your code handles a failed sync.
private class MockServerError implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(500);
res.setBody('{"error":"unavailable"}');
return res;
}
}You can also assert on the request itself. Inside respond, check req.getEndpoint() equals callout:Billing_API/accounts and req.getMethod() equals POST. A failed assertion inside a mock fails the test, which catches wrong endpoints early.
Exercise
Your test inserts an Account and asserts that a Queueable callout completed, but the assertion fails because no completed job is found. The mock is registered correctly. What is the most likely missing line, and why does it matter?
Show answer
Test.stopTest() is missing or placed after the assertion. Queued asynchronous jobs only run when stopTest() is called, so before that point the job has not executed and no completed AsyncApexJob record exists.