Saturday, April 19, 2025
HomeInterview QuestionHow to Write Test class for Apex REST - Salesforce Interview Question

How to Write Test class for Apex REST – Salesforce Interview Question

Telegram Group Join Now
whatsApp Channel Join Now
5/5 - (1 vote)

Salesforce Interview Question – How to create a mock callout to test the Apex rest callout in Salesforce? or How to Write Test class for Apex REST: By default, test methods don’t support web service callouts, and tests that perform web service callouts fail. Apex provides the built-in WebServiceMock interface and the Test.setMock method to prevent tests from failing.

Further, the Apex test class will not let us conduct an HTTP callout. Hence, you cannot test external APIs. But, Apex does have an interface called HttpCalloutMock for standard callout tests.

Apex Class Code:

public class Animals {
    public static HttpResponse animals() {
        Http http = new Http();
        HttpRequest req = new HttpRequest();
        req.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals');
        req.setMethod('POST');
        req.setHeader('Content-Type', 'application/json;charset=UTF-8');
        req.setBody('{"Name":"Lion"}');
        
        HttpResponse res = http.send(req);
        
        if (res.getStatusCode() == 200) {
            System.debug(res.getBody());
        } else {
            System.debug('Error. Status: ' + res.getStatusCode());
        }
        return res;
    }
}

Mock Class Code:

@isTest
global class AnimalsCalloutMock implements HttpCalloutMock {
    global HttpResponse respond(HttpRequest req) {
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"Animals":["Horse","Dog","Tiger","Lion","Cat","Mouse"]}');
        res.setStatusCode(200);
        return res;
    }
}

Apex Test Class Code:

@isTest
public class AnimalsTest {
    @isTest
    static void testAnimals() {
        // Set the mock callout response
        Test.setMock(HttpCalloutMock.class, new AnimalsCalloutMock());
        
        // Call the method that makes the HTTP callout
        HttpResponse res = Animals.animals();
        String expected = '{"Animals":["Horse","Dog","Tiger","Lion","Cat","Mouse"]}';
        
        // Assert the response status and body
        System.assertEquals(200, res.getStatusCode());
        System.assertEquals(expected, res.getBody());
    }
}

Conclusion for How to Write Test class for Apex REST

And that’s it! You now have a complete solution for mocking callouts to test Apex REST callouts in Salesforce. We hope this guide was helpful in understanding how to write a test class for a REST API. If you implement this approach in your projects, we’d love to hear about your experience! Stay tuned for more Salesforce solutions next week. Until then, happy coding! 🚀

RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments