# What best practices ensure high code quality and test robustness for Apex integration unit tests?

**Topic:** Integration · **Difficulty:** Medium · **Tags:** Integration, Unit Testing, Test Coverage Best Practices

Read it on the site: https://www.forcechallenges.com/interview-questions/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:**
1. Create a mock implementing respond(HttpRequest) that returns an HttpResponse (status, body, headers).
2. In the test: set up data with @testSetup or a factory, call Test.setMock, then Test.startTest(), run the code, Test.stopTest().
3. Assert the result, saved records, and optionally that the mock saw the expected endpoint, method and body.
4. 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:**
```apex
@IsTest
private class InventoryClientTest {
    private class Mock implements HttpCalloutMock {
        Integer status; String body;
        Mock(Integer s, String b) { status = s; body = b; }
        public HttpResponse respond(HttpRequest req) {
            Assert.areEqual('GET', req.getMethod());
            HttpResponse r = new HttpResponse();
            r.setStatusCode(status); r.setBody(body); return r;
        }
    }
    @IsTest static void success() {
        Test.setMock(HttpCalloutMock.class, new Mock(200, '{"qty":5}'));
        Test.startTest();
        String res = InventoryClient.getStock('SKU1');
        Test.stopTest();
        Assert.isTrue(res.contains('"qty":5'));
    }
    @IsTest static void serverError() {
        Test.setMock(HttpCalloutMock.class, new Mock(500, '{}'));
        try { Test.startTest(); InventoryClient.getStock('SKU1'); Test.stopTest(); Assert.fail('Expected exception'); }
        catch (CalloutException e) { Assert.isTrue(e.getMessage().contains('500')); }
    }
}
```

**Hidden gotchas & must-remember points:**
- Real callouts fail in tests with "Methods defined as TestMethod do not support Web service callouts".
- Set the mock before invoking the code, including before async jobs run.
- Async jobs execute at Test.stopTest().
- 75% overall coverage is a deploy gate, not a quality measure.
- Test with 200 records for triggers/bulk.
- Do not hardcode record Ids or rely on org data (no SeeAllData).

**Best practice:** Assert behavior for success, each error class and timeouts, and keep mocks small and reusable.

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