ApexSensei

Drills › Prove it with tests

Mock an HTTP callout

Prove it with tests · Intermediate · 16 min · Runs in your Salesforce Developer org · Apex Path

Scenario. A status client calls an outside API. Its tests must stay offline and give the same result every time.

Implement HttpCalloutMock and register it with Test.setMock so a client can be tested offline.

What you will learn

Tests can't make real HTTP callouts. Write a class that implements HttpCalloutMock. Its respond builds the response your code gets. Register with Test.setMock before the call.

Test.setMock(HttpCalloutMock.class, new MyMock());

@TestVisible lets a test read a private field real callers shouldn't see. Provided code uses it on lastRequest.

Gotcha. DML before a callout in one test gives "uncommitted work pending". DML before Test.startTest(), callout after.

The task

Finish the mock so the provided HTTP client can be tested with no network, and make your own test register it.

Examples:

  • default mock → the client returns {"ok":true}
  • statusCode = 500 → the client throws a CalloutException whose message contains 500
  • fetchesOkBody() → calls Test.setMock with this mock, then calls the client

Requirements:

  1. respond returns a new HttpResponse built from the statusCode and body fields.
  2. Keep statusCode and body public. The checks change them.
  3. In fetchesOkBody, call Test.setMock before fetchStatus, then assert the body.
  4. Keep fetchesOkBody public static. The checks set their own mock, then call it, so yours must replace theirs.

Starter code

@IsTest
public class AS_0199CD2979A4_Mock implements HttpCalloutMock {
    public Integer statusCode = 200;
    public String body = '{"ok":true}';

    public HttpResponse respond(HttpRequest req) {
        return null;
    }

    @IsTest
    public static void fetchesOkBody() {
        String result = AS_0199CD2979A4_Client.fetchStatus();
        Assert.areEqual('{"ok":true}', result);
    }
}

When it passes

The mock returns a response built from its fields, the client throws on 400 or higher, and fetchesOkBody registers the mock before it calls the client.

Try this drill free

You write the Apex yourself. ApexSensei runs it and tells you what passed and what did not.

‹ Use a fake collaborator · Share setup and run as another user ›