Sub topic 14
Best practices and common pitfalls
This chapter pulls together what the earlier chapters built. It assumes you can write an HttpCalloutMock, register it with Test.setMock, and write basic success and error tests. It covers the habits that keep callout tests reliable and the errors you are most likely to hit.
Keep the mock outside the production path
A callout test should exercise your real code and replace only the network. Follow these rules.
- Never add
Test.isRunningTest()branches to production code that skip the callout. They hide the code you meant to test and leave dead paths in production. - Keep mock classes
@IsTest. They then never count against org code size and cannot be called from production code. - Put the endpoint, headers, and parsing in one place, such as
WeatherService. A test then needs one mock for one unit of behavior. - Use realistic bodies. Copy a real response from the API documentation or from a logged response, then trim it. A mock that returns
{"condition":"Sunny"}when the real API returns nested objects proves little. - Do not use
@IsTest(SeeAllData=true)to reach existing records. Create the data your test needs.
Cover the failure paths, not only the happy path
The most common weakness in callout tests is coverage that only reaches the 200 branch. A callout can fail in several distinct ways, and each one needs its own test.
| Failure | How to simulate it | What to assert |
|---|---|---|
| Non-200 status | `new WeatherServiceMock(500, '...')` | Your exception type and message |
| 4xx with an error body | `new WeatherServiceMock(404, '{"error":"not found"}')` | The code handles the error body shape |
| Malformed or empty body | A mock returning `'{"condition":'` or `''` | A controlled failure, not an unhandled `JSONException` |
| Network failure or timeout | A mock that throws `CalloutException` from `respond` | The exception propagates or is handled as designed |
A mock can throw from respond. The exception then surfaces from Http.send, exactly as a timeout would:
@IsTest
public class ThrowingMock implements HttpCalloutMock {
public HttpResponse respond(HttpRequest req) {
throw new CalloutException('Read timed out');
}
}@IsTest
private class WeatherServiceFailureTest {
@IsTest
static void propagatesTimeout() {
Test.setMock(HttpCalloutMock.class, new ThrowingMock());
Test.startTest();
try {
WeatherService.getCondition('Oslo');
Assert.fail('Expected a CalloutException');
} catch (CalloutException e) {
Assert.areEqual('Read timed out', e.getMessage(), 'The mock message should surface');
}
Test.stopTest();
}
}Assert.fail throws an AssertException, which the catch (CalloutException e) block does not match. If the code under test fails to throw, the test fails as intended.
Malformed bodies deserve special attention. WeatherService.getCondition as written does not catch JSONException, so a truncated body would escape as a raw parsing error. A test that sends '{"condition":' shows you that gap. You can then decide whether to wrap the parse in a try/catch and throw WeatherException.
Order setup DML around the callout
Salesforce does not allow a callout after uncommitted DML in the same transaction. A test that inserts records and then calls the service fails with:
System.CalloutException: You have uncommitted work pending. Please commit or rollback before calling out
The fix is to put the callout between Test.startTest() and Test.stopTest(). startTest gives the code inside it a fresh set of governor limits and clears the pending-work restriction.
@IsTest
private class WeatherDmlOrderTest {
@IsTest
static void calloutAfterSetupDml() {
Account acct = new Account(Name = 'Oslo Office');
insert acct;
Test.setMock(HttpCalloutMock.class, new WeatherServiceMock(200, '{"condition":"Sunny"}'));
Test.startTest();
String condition = WeatherService.getCondition('Oslo');
Test.stopTest();
Assert.areEqual('Sunny', condition, 'Callout should succeed after setup DML');
}
}This is only a test-side fix. If your production code does DML and then a callout in one transaction, it fails in production too. Reorder it, or move the callout to a Queueable.
Assert on something real
Weak assertions let broken code pass. Watch for these.
Assert.isTrue(true, ...)asserts nothing. The Queueable test in the earlier chapter only proves that no exception was thrown. Make the job write a result you can query afterTest.stopTest(), such as a field on a record, and assert on that.Assert.isNotNull(condition)passes for any non-null string. PreferAssert.areEqualwith the exact expected value from your mock body.- Always give a message argument. A failure then names what broke without you opening the test.
- Assert on the request too.
RoutingMockrecords every request, so after the callout you can checkmock.requests.size(), the method, the endpoint, and the headers. This catches a wrong URL or a missingAcceptheader that a canned response would never reveal.
Common errors and what they mean
| Symptom | Likely cause | Fix |
|---|---|---|
| `Methods defined as TestMethod do not support Web service callouts` | No mock was registered before the callout | Call `Test.setMock` before the code that sends the request |
| `You have uncommitted work pending` | DML ran before the callout in the same transaction | Wrap the callout in `Test.startTest` and `Test.stopTest` |
| Mock returns 404 and "No mock registered" | The routing key does not match the real method and endpoint | Compare the exact URL, including query-string encoding such as `city=Oslo` |
| `System.TypeException: Invalid conversion from runtime type...` | The mock body shape differs from what the parser casts to | Make the mock body match the real API response shape |
| Queueable test passes but nothing happened | The test never reached `Test.stopTest`, or asserted nothing | Assert on saved results after `stopTest` |
| `Test.setMock` seems ignored | The mock was set after the callout, or the class does not implement `HttpCalloutMock` | Set it first and check the interface |
The routing mismatch deserves care. If the code builds its endpoint with EncodingUtil.urlEncode, the registered key must use the encoded form. A city such as New York becomes New+York in the URL.
A quick way to diagnose a failing callout test
Keep tests fast and independent
- Reuse mocks, such as
WeatherServiceMockwith different constructor arguments, rather than writing one class per response. - Build only the records each test needs. Shared setup in
@TestSetupis fine, but remember its DML still happens before your callout, so thestartTestrule applies. - Don't rely on the order of tests or on data from another test method. Each method runs in its own rolled-back transaction.
- Callout limits still apply in tests. A single transaction allows 100 callouts. A loop that calls the service once per record will hit that limit with large test data, and it will also hit it in production.
- A chained Queueable does not run its child job inside a test. Test each job's
executelogic separately, for example by callingnew WeatherSyncJob('Oslo').execute(null)with a mock set.
Quick checklist
- Register a mock before every callout, in every test method that reaches one.
- Cover success, 4xx, 5xx, malformed body, and thrown
CalloutException. - Put setup DML before
Test.startTest()and the callout inside it. - Assert on exact values, and on the outgoing request where it matters.
- Keep production code free of test-only branches.
- Use realistic mock bodies, kept in a static resource when they are large.
Exercise
A test inserts an Account, calls Test.setMock, and then calls WeatherService.getCondition('Oslo') directly, with no Test.startTest. It fails with "You have uncommitted work pending". What is the smallest change that fixes it, and why does it work?
Show answer
Wrap the callout in Test.startTest() and Test.stopTest(), with the DML and Test.setMock before startTest. startTest starts a fresh set of limits and clears the pending-work restriction, so the callout is allowed. The production code is unchanged, because the restriction is a transaction rule that the test boundary resets.
Exercise
Why is Assert.isTrue(true, 'Job ran to completion') a weak check for the Queueable test, and what would you do instead?
Show answer
It always passes, so it cannot detect a job that failed silently or produced the wrong result. Change the job to save its outcome, for example by updating a record field with the returned condition. Then, after Test.stopTest(), query that record and assert on the exact value from the mock body.