Salesforce – Mock callouts in Apex

assorted color vehicle vehicle on street
Reading Time: < 1 minutes

To mock callouts in Apex, you can create a class that implements the HttpCalloutMock interface. This allows you to define the desired response for an HTTP request made during testing. Here’s an example of how you can create a mock class for callouts:

   private class RestMock implements HttpCalloutMock {

        public HTTPResponse respond(HTTPRequest req) {
            HTTPResponse res = new HTTPResponse();
            res.setHeader('Content-Type', 'text/json');
            return res;

In your test method, you can use the Test.setMock method to associate your mock class with the HTTP callout. Here’s an example of how to use the mock in a test:

@isTest static void myTest() {
        Test.setMock(HttpCalloutMock.class, new RestMock());
        // Some stuff...

        // Test-related stuff...

By using this approach, you can simulate different scenarios and responses to ensure your code handles callouts correctly during testing.


About the author

Andrés Canavesi
Andrés Canavesi

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

Related posts

Leave a Reply

%d bloggers like this: