Sub topic 12
Testing with HttpCalloutMock
This chapter assumes you can write an Apex test class with @IsTest methods and assertions. It also assumes you have read the earlier chapters, so you know the trigger, the AccountSyncJob Queueable, and its AccountSyncFinalizer. Here you test that whole chain without a real network call.
Why tests need a mock
Apex tests are not allowed to make real HTTP callouts. If code under test calls new Http().send(req) and no mock is registered, the test fails with this error:
System.CalloutException: Methods defined as TestMethod do not support Web service calloutsThe restriction also protects you. A test run should not depend on a billing service being up, and it should not create real records in someone's system. A mock replaces the HTTP layer. The code under test runs unchanged, but send() returns a response you control.
The mock is a class that implements the HttpCalloutMock interface. The interface has one method, respond(HttpRequest req), which returns an HttpResponse. You register an instance with Test.setMock(HttpCalloutMock.class, mock). After that, every callout in the test context goes to your respond method.
How the pieces run in a test
Asynchronous work does not run immediately in a test. Salesforce holds queued jobs and future calls until Test.stopTest() is called. At that point it runs them synchronously, and your code continues only after they finish.
Three consequences follow from this.
- Call
Test.setMockbefore the code that makes the callout runs. Putting it beforeTest.startTest()is the safe convention. - Assertions about the job's effects must come after
Test.stopTest(). Before that point the job has not run. - Jobs queued by a trigger run in their own transaction. This is why a trigger-then-callout flow works in production, and it works the same way in tests.
A basic test
This is the test from the plan. It checks that inserting one account causes the Queueable to run to completion.
@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');
}
}This proves the job ran. It does not prove the job sent the right request. A job that posted an empty body would pass too. To close that gap, make the mock record what it receives.
A mock that records requests
The mock class can hold state in instance fields, and the test reads those fields after Test.stopTest(). Use instance fields, not static ones. Apex does not allow static members in inner classes, and keeping the mock inside the test class is the usual pattern.
@IsTest
private class AccountSyncJobRequestTest {
private class RecordingMock implements HttpCalloutMock {
public Integer statusCode;
public Integer callCount = 0;
public List<HttpRequest> requests = new List<HttpRequest>();
public RecordingMock(Integer statusCode) {
this.statusCode = statusCode;
}
public HttpResponse respond(HttpRequest req) {
callCount++;
requests.add(req);
HttpResponse res = new HttpResponse();
res.setStatusCode(statusCode);
res.setBody('{}');
return res;
}
}
@IsTest
static void sendsOnePostWithTheAccountName() {
RecordingMock mock = new RecordingMock(200);
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
System.assertEquals(1, mock.callCount, 'Exactly one callout expected');
HttpRequest sent = mock.requests[0];
System.assertEquals('POST', sent.getMethod());
System.assert(sent.getEndpoint().contains('/accounts'), 'Unexpected endpoint: ' + sent.getEndpoint());
System.assert(sent.getBody().contains('Acme'), 'Body should contain the account name');
}
}The endpoint assertion uses contains on purpose. With a Named Credential the endpoint starts with callout:Billing_API, and you should not tie the test to how the platform expands it.
Testing the bulk path
The chapter on bulk safety claimed that one trigger transaction produces one job and one callout, however many records it inserts. A test should enforce that claim. Insert 200 accounts, which is one full trigger batch, and count the requests.
@IsTest
private class AccountSyncBulkTest {
private class CountingMock implements HttpCalloutMock {
public Integer callCount = 0;
public String lastBody;
public HttpResponse respond(HttpRequest req) {
callCount++;
lastBody = req.getBody();
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void twoHundredAccountsProduceOneCallout() {
CountingMock mock = new CountingMock();
Test.setMock(HttpCalloutMock.class, mock);
List<Account> accounts = new List<Account>();
for (Integer i = 0; i < 200; i++) {
accounts.add(new Account(Name = 'Bulk ' + i));
}
Test.startTest();
insert accounts;
Test.stopTest();
System.assertEquals(1, mock.callCount, 'One batch should mean one callout');
List<Object> sent = (List<Object>) JSON.deserializeUntyped(mock.lastBody);
System.assertEquals(200, sent.size(), 'All accounts should be in the payload');
}
}If someone later changes the trigger to enqueue one job per record, this test fails because callCount becomes 200. The platform would also reject that design in production, since a single transaction can enqueue only a limited number of jobs. The test catches the mistake before deployment.
Testing the failure path
The job logs an error when the status code is outside the 200 range. Use the recording mock with a 500 status to confirm the job handles a failed response without crashing.
@IsTest
private class AccountSyncFailureTest {
private class FailingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
HttpResponse res = new HttpResponse();
res.setStatusCode(500);
res.setBody('{"error":"server down"}');
return res;
}
}
@IsTest
static void serverErrorDoesNotFailTheJob() {
Test.setMock(HttpCalloutMock.class, new FailingMock());
Test.startTest();
insert new Account(Name = 'Acme');
Test.stopTest();
Integer failed = [
SELECT COUNT() FROM AsyncApexJob
WHERE JobType = 'Queueable' AND ApexClass.Name = 'AccountSyncJob' AND Status = 'Failed'
];
System.assertEquals(0, failed, 'A 500 response is handled, not thrown');
}
}The test also confirms that the account insert itself succeeds. The user's save is never affected by a failed sync, which is the main benefit of moving the callout out of the trigger.
Testing a future method
A @future(callout=true) method follows the same rules. Register the mock, call the method between startTest and stopTest, and assert afterwards.
@IsTest
private class AccountCalloutServiceTest {
private class MockOk implements HttpCalloutMock {
public Integer callCount = 0;
public HttpResponse respond(HttpRequest req) {
callCount++;
HttpResponse res = new HttpResponse();
res.setStatusCode(200);
res.setBody('{}');
return res;
}
}
@IsTest
static void futureMethodMakesOneCallout() {
Account a = new Account(Name = 'Acme');
insert a;
MockOk mock = new MockOk();
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
AccountCalloutService.syncAccounts(new Set<Id>{ a.Id });
Test.stopTest();
System.assertEquals(1, mock.callCount);
}
}Here the account is inserted before Test.startTest(). If your test does DML and then calls a method that makes a callout in the same synchronous flow, you can hit the "uncommitted work pending" error. Wrapping the callout in a future method, as here, avoids it, because the method runs in its own transaction.
Common errors
| Symptom | Likely cause | Fix |
|---|---|---|
| `Methods defined as TestMethod do not support Web service callouts` | No mock registered, or `Test.setMock` came after the callout ran | Call `Test.setMock` before `Test.startTest()` |
| Assertion on job results fails, and the job shows as `Queued` or is missing | Assertion placed before `Test.stopTest()` | Move assertions after `stopTest` |
| Compile error about static members in the mock | Static field declared in an inner class | Use instance fields and keep a reference to the mock |
| Mock counts are 0 | The trigger did not fire, or the test inserted records the trigger ignores | Check trigger conditions and test data |
| Calling `new AccountSyncJob(ids).execute(null)` fails | `System.attachFinalizer` needs a real Queueable context | Enqueue the job between `startTest` and `stopTest` instead |
Other mock helpers
For simple cases you do not have to write a class. StaticResourceCalloutMock returns the body of a static resource, and MultiStaticResourceCalloutMock maps different endpoints to different resources. Write a custom HttpCalloutMock when you need to inspect the request, as in the examples above, or to vary the response by request content.
Exercise
A test inserts an Account, then immediately queries AsyncApexJob for a Completed AccountSyncJob and finds none. It has Test.setMock before the insert and wraps nothing in Test.startTest()/Test.stopTest(). What is wrong, and what is the fix?
Show answer
Queued jobs do not run during the test method on their own. They run when Test.stopTest() is called. Without that call, the job never executes, so no Completed job exists. Wrap the insert in Test.startTest() and Test.stopTest(), and run the query after stopTest().
Exercise
Write the assertion that makes the bulk test fail if a developer changes the trigger to enqueue one job per account, given a mock with a callCount field.
Show answer
System.assertEquals(1, mock.callCount, 'One batch should mean one callout'); After inserting 200 accounts, a per-record design would send 200 requests, so callCount would be 200 and the assertion would fail.