# How do mock testing frameworks simulate negative server scenarios during integration unit test executions?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Mock Testing, Error Simulation

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Write a class implementing `HttpCalloutMock` with `HttpResponse respond(HttpRequest req)`.
2. In the test, call `Test.setMock(HttpCalloutMock.class, new MyMock(500));`.
3. Call the code under test inside `Test.startTest()` / `Test.stopTest()`.
4. Assert on the outcome: log rows written, retry flags set, exceptions handled.
5. Variants: `StaticResourceCalloutMock` returns a static resource body; `MultiStaticResourceCalloutMock` maps endpoints to resources; `WebServiceMock` is 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:**
```apex
@IsTest
private class ErpClientTest {
    private class FailMock implements HttpCalloutMock {
        Integer code; FailMock(Integer c) { code = c; }
        public HttpResponse respond(HttpRequest req) {
            if (code == 0) throw new CalloutException('Read timed out');
            HttpResponse r = new HttpResponse();
            r.setStatusCode(code); r.setBody('{"error":"server"}');
            return r;
        }
    }
    @IsTest static void handles500() {
        Test.setMock(HttpCalloutMock.class, new FailMock(500));
        Test.startTest();
        Boolean ok = ErpClient.send('payload');
        Test.stopTest();
        System.assertEquals(false, ok, 'Should report failure on 500');
    }
    @IsTest static void handlesTimeout() {
        Test.setMock(HttpCalloutMock.class, new FailMock(0));
        Test.startTest(); Boolean ok = ErpClient.send('payload'); Test.stopTest();
        System.assertEquals(false, ok);
    }
}
```

**Hidden gotchas & must-remember points:**
- No mock set means "Methods defined as TestMethod do not support Web service callouts".
- DML before a callout in the same test context triggers "uncommitted work pending" unless separated by startTest.
- Mock must match the callout type (HTTP vs SOAP `WebServiceMock`).
- Async jobs run at `Test.stopTest()`.
- Only one mock per type is active at a time; the latest `setMock` wins.
- Use `Test.getEventBus().deliver()` to deliver platform events in tests.

**Best practice:** Test every failure branch with a dedicated mock and assert the observable recovery behavior.

---
Source: ForceChallenges · last updated 2026-11-02
