Sub topic 14
Best practices and common pitfalls
This chapter pulls together the habits that keep callout tests reliable. It assumes you can write an HttpCalloutMock, register it with Test.setMock, and run a test with @IsTest. You should also know basic HTTP status codes and JSON.
Habits that keep callout tests healthy
- Cover both paths. Test at least one success response and one error response. A callout class that only has a 200 test hides its failure handling.
- Assert on results, not on "no exception". A test that only runs the code proves little. Check the returned value, the exception message, or the request that was sent.
- Reuse one parameterized mock. A mock that takes a status code and body in its constructor, like
WeatherServiceMock, avoids a new class for every case. - Use a routing mock for multi-step flows. When one method makes several callouts, register each method and endpoint pair and return a clear 404 for anything unregistered. A missing route then fails loudly.
- Keep large bodies out of Apex. Use
StaticResourceCalloutMockfor long JSON so the test stays readable. - Keep the callout in one place. Put the
Http.sendcall in a small service class. Business logic can then be tested with simple inputs.
Common pitfalls
| Pitfall | What happens | Fix |
|---|---|---|
| Calling `Test.setMock` after the callout | The test fails with "Methods defined as TestMethod do not support Web service callouts" | Register the mock before any code that can call out |
| Making DML before a callout in the same transaction | A "You have uncommitted work pending" error | Do the callout first, or wrap the DML in `Test.startTest()` and `Test.stopTest()` so it runs in a separate context |
| Missing `Database.AllowsCallouts` on a Queueable | A callout error at runtime | Add the interface to the job class |
| Wrong endpoint string in a routing mock | The mock returns 404 and the test fails oddly | Build the expected key from the same constant or helper the code uses |
| Static resource name misspelled | The test fails at runtime | Check the name matches the resource in the org exactly |
| Asserting `true` after a job runs | The test can never fail | Assert on data the job changed |
A test that verifies more than the output
The routing mock from earlier records every request. Use that record to check what your code actually sent.
@IsTest
private class WeatherServiceRequestTest {
@IsTest
static void sendsEncodedCityAndAcceptHeader() {
RoutingMock mock = new RoutingMock();
mock.add('GET', 'https://api.example.com/weather?city=New+York', 200, '{"condition":"Cloudy"}');
Test.setMock(HttpCalloutMock.class, mock);
Test.startTest();
String condition = WeatherService.getCondition('New York');
Test.stopTest();
Assert.areEqual('Cloudy', condition, 'The body should be parsed');
Assert.areEqual(1, mock.requests.size(), 'Exactly one callout expected');
Assert.areEqual('application/json', mock.requests[0].getHeader('Accept'), 'Accept header should be set');
}
}This test fails if the city is not URL-encoded, because the route key would not match and the mock would return 404. It also fails if the code makes an extra callout.
Quick checklist
- The mock is registered before the first callout.
- There is a success test and an error test.
- Assertions check values, not just that the code ran.
- Asynchronous code is enqueued between
Test.startTest()andTest.stopTest(). - No test depends on a real endpoint or on org data you did not create.
Exercise
A test inserts an Account, then calls WeatherService.getCondition('Oslo') with a mock registered, and fails with "You have uncommitted work pending". How can you fix the test without changing WeatherService?
Show answer
Move the DML so it does not share a context with the callout. Put the Account insert before Test.startTest() and the callout between Test.startTest() and Test.stopTest(). Test.startTest() starts a fresh context, so the pending DML no longer blocks the callout.
Exercise
Why does the routing mock return a 404 for unregistered calls instead of an empty 200 response?
Show answer
A 404 makes a missing or mistyped route fail visibly. An empty 200 could let the code parse bad data and pass the test for the wrong reason.