What best practices ensure high code quality and test robustness for Apex integration unit tests?
Answer
Basics: Apex tests cannot make real HTTP callouts. You supply a mock class implementing HttpCalloutMock (or WebServiceMock for SOAP) and register it with Test.setMock. The platform then returns your fake response. Coverage of 75% is required to deploy, but meaningful assertions are what prove the integration works.
How it works:
- Create a mock implementing respond(HttpRequest) that returns an HttpResponse (status, body, headers).
- In the test: set up data with @testSetup or a factory, call Test.setMock, then Test.startTest(), run the code, Test.stopTest().
- Assert the result, saved records, and optionally that the mock saw the expected endpoint, method and body.
- Repeat with error mocks: 400, 401, 500, malformed JSON, and a thrown CalloutException.
Advanced / deep dive: Use StaticResourceCalloutMock for canned JSON files and MultiStaticResourceCalloutMock for multiple endpoints. For sequences (first call 401, retry 200) build a mock with a counter. Asynchronous code (Queueable, @future, Batch) runs when Test.stopTest() is called, so mock must be set first. If test setup does DML before the callout, put the callout inside Test.startTest/stopTest to avoid "uncommitted work pending". Test bulk: 200 records to verify no limits are hit (callouts per transaction at 100). Platform events and CDC: Test.getEventBus().deliver() and Test.enableChangeDataCapture(). Prefer the Assert class (Assert.areEqual, Assert.isTrue). Keep production code injectable (an interface or Named Credential) so you do not depend on URLs.
Code / config example:
@IsTest
private class InventoryClientTest {
{
Integer status; String body;
Mock(Integer s, String b) { status = s; body = b; }
HttpResponse {
Assert.areEqual(, req.getMethod());
();
r.setStatusCode(status); r.setBody(body); r;
}
}
{
Test.setMock(HttpCalloutMock.class, (, ));
Test.startTest();
InventoryClient.getStock();
Test.stopTest();
Assert.isTrue(res.contains());
}
{
Test.setMock(HttpCalloutMock.class, (, ));
{ Test.startTest(); InventoryClient.getStock(); Test.stopTest(); Assert.fail(); }
(CalloutException e) { Assert.isTrue(e.getMessage().contains()); }
}
}