How do mock testing frameworks simulate negative server scenarios during integration unit test executions?
Answer
Basics: Apex tests are not allowed to make real callouts, so any code that calls out fails the test unless a mock is registered. Mocks let you control the response and prove your code handles 200s, 4xx, 5xx and timeouts.
How it works:
- Write a class implementing
HttpCalloutMockwithHttpResponse respond(HttpRequest req). - In the test, call
Test.setMock(HttpCalloutMock.class, new MyMock(500));. - Call the code under test inside
Test.startTest()/Test.stopTest(). - Assert on the outcome: log rows written, retry flags set, exceptions handled.
- Variants:
StaticResourceCalloutMockreturns a static resource body;MultiStaticResourceCalloutMockmaps endpoints to resources;WebServiceMockis for SOAP/WSDL-generated code.
Advanced / deep dive: Timeouts cannot be truly simulated, but throwing a CalloutException from respond replicates a failed call. Use a parameterized or sequential mock to return different responses per call (e.g., 503 then 200 to test retry). For async code (Queueable/Batch/@future), enqueue inside startTest/stopTest so the job runs synchronously at stopTest, with the mock still active. To test Platform Events, Test.getEventBus().deliver() forces delivery. Avoid "uncommitted work pending": perform setup DML before startTest or isolate. Named Credentials still require a mock in tests. Assert on behavior, not just coverage (75% minimum coverage for deployment is not the goal).
Code / config example:
@IsTest
{
{
Integer code; FailMock(Integer c) { code = c; }
HttpResponse {
(code == ) ();
();
r.setStatusCode(code); r.setBody();
r;
}
}
{
Test.setMock(HttpCalloutMock.class, ());
Test.startTest();
ErpClient.send();
Test.stopTest();
System.assertEquals(, ok, );
}
{
Test.setMock(HttpCalloutMock.class, ());
Test.startTest(); ErpClient.send(); Test.stopTest();
System.assertEquals(, ok);
}
}