How do developers utilize HttpCalloutMock interfaces to test Apex callout logic successfully during unit tests?
Answer
Basics: Apex tests are not allowed to make real HTTP callouts; without a mock the test fails with "Methods defined as TestMethod do not support Web service callouts". A mock class returns a canned HttpResponse, letting you test success, error codes, bad JSON and timeouts. Salesforce requires 75% overall Apex coverage to deploy to production, and callout code cannot be covered without mocks.
How it works:
- Create a class implementing
HttpCalloutMockwithHttpResponse respond(HttpRequest req). - In the test, call
Test.setMock(HttpCalloutMock.class, new MyMock());before invoking the callout. - Run the code (inside
Test.startTest()/Test.stopTest()for async code) and assert on results. - For SOAP callouts from WSDL2Apex use
WebServiceMock; forContinuationuseTest.setContinuationResponseandTest.invokeContinuationMethod.
Advanced / deep dive: One mock can serve multiple endpoints by branching on req.getEndpoint() and req.getMethod(), or use MultiStaticResourceCalloutMock with JSON files in static resources. Capture the request in a static field to assert headers and body. Test error paths: return status 500 or 429, or throw a CalloutException from respond. For queueable or future callouts, the mock applies when the async job runs at Test.stopTest(). To avoid "uncommitted work pending" in tests, create data in @testSetup (which commits) rather than DML right before the callout. For stronger design, wrap callouts behind an interface or service class so higher-level tests can inject a stub instead of mocking HTTP. Assertions matter: coverage alone is not quality.