Test Class for Apex REST Callout

A Developer wants to implement a connection from Salesforce to a 3rd party API using Apex; A great method for retrieving external data is to implement a HTTP callout process using Apex.

How can we run test class for callout ? As you may know, Apex Test Classes will not let us conduct a HTTP callout; therefore, it cannot be used to test External APIs. However, there is a solution wherein Apex has an interface called HttpCalloutMock for standard callout tests.

We already have a blog to showcase the Rest Callout to our Salesforce Rest Service (Considering a third party service) using apex:

https://apexcoder.com/2017/01/26/how-to-call-rest-service-using-oauth-rest-api/

We are going to implement the test class for above mentioned blog’s code:-

@isTest
global class MockHttpResponseGenerator implements HttpCalloutMock {
    // Implement this interface method
    global HTTPResponse respond(HTTPRequest req) {
        // Optionally, only send a mock response for a specific endpoint
        // and method.
        System.assertEquals('http://example.com/example/test', req.getEndpoint());
        System.assertEquals('GET', req.getMethod());
        
        // Create a fake response
        HttpResponse res = new HttpResponse();
        res.setHeader('Content-Type', 'application/json');
        res.setBody('{"example":"test"}');
        res.setStatusCode(200);
        return res;
    }
}

@isTest
private class CalloutClassTest {
     @isTest static void testCallout() {
        // Set mock callout class 
        Test.setMock(HttpCalloutMock.class, new MockHttpResponseGenerator());
        
        // Call method to test.
        // This causes a fake response to be sent
        // from the class that implements HttpCalloutMock. 
        MyCalloutService tw = new MyCalloutService();
        tw.methodGet();

    }
}

 

In the above code, we have created a Mock response using apex class “MockHttpResponseGenerator” which helps to create a sample mock call and return the response to test class “CalloutClassTest” which invokes the actual callout.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s