Example of Apex HttpCalloutMock

Example of  Apex HttpCalloutMock
Reading Time: 2 minutes

In Apex, you can use the HttpCalloutMock interface to mock HTTP callouts when writing unit tests for code that makes HTTP requests. This allows you to control the responses returned by the mock instead of making actual HTTP requests during testing. Here’s an example of how to use HttpCalloutMock in Apex:

Let’s say you have a class that makes an HTTP callout to an external service, and you want to write a unit test for it. First, you need to create a mock class that implements the HttpCalloutMock interface. This mock class will simulate the HTTP response you expect:

public class MyHttpCalloutMock implements HttpCalloutMock {
    // Implement the respond method to simulate the HTTP response.
    public HTTPResponse respond(HTTPRequest request) {
        // Create a new HTTPResponse object to mock the response.
        HTTPResponse response = new HTTPResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"message": "Mocked response"}');

        return response;

In this example, MyHttpCalloutMock implements the HttpCalloutMock interface and provides a mock response with a JSON body and a 200 status code.

Now, you can use this mock class in your unit test to simulate the HTTP callout:

public class MyHttpCalloutTest {
    @isTest static void testHttpCallout() {
        // Create an instance of the HttpCalloutMock class.
        HttpCalloutMock mock = new MyHttpCalloutMock();

        // Set the mock in the test context.
        Test.setMock(HttpCalloutMock.class, mock);

        // Call your code that makes the HTTP callout.
        // Replace this with the actual call to your HTTP request method.
        String response = MyHttpCalloutClass.makeHttpCallout();

        // Perform assertions on the response.
        System.assertEquals('{"message": "Mocked response"}', response);

In the testHttpCallout method, we set the MyHttpCalloutMock as the mock for HTTP callouts using Test.setMock(). Then, we call the code that makes the HTTP callout, which will now use the mock response provided by MyHttpCalloutMock. Finally, we assert that the response matches the expected value.

This way, you can write unit tests for code that makes HTTP callouts without actually making external requests, ensuring predictable and controlled testing conditions.


About the author

Andrés Canavesi
Andrés Canavesi

Software Engineer with 15+ experience in software development, specialized in Salesforce, Java and Node.js.

Join 22 other subscribers

Leave a Reply