Thursday, July 6, 2017

Different ways of testing HTTP callout in apex

As we all know that test methods do not support HTTP callout, so all test method performing callout will fail.

In order to avoid the test class failure, we mainly use Test.IsRunningTest method in apex class. By using this method, we make sure that particular block of code performing HTTP callout should not run when called by test class methods.
if(!Test.isRunningTest()){
// apex code for HTTP callout
}
but this approach will reduce your code coverage. As per salesforce, you need to have atleast 75% coverage for all your apex code.

We will now go through different options through which we can test HTTP callout and increase our code coverage.
  • Using static resource
You can store the response of your HTTP callout in text file and upload it static resource. Now you can use built in apex class StaticResourceCalloutMock or MultiStaticResourceCalloutMock to build mock response and get response from static resource.

First create an instance of StaticResourceCalloutMock:

StaticResourceCalloutMock mockCallout = new StaticResourceCalloutMock();
mockCallout.setStaticResource('StaticResourceForCallout');
mockCallout.setStatusCode(200);
mockCallout.setHeader('Content-Type', 'application/json');

Now set mock callout mode in test method by using below method:

Test.setMock(HttpCalloutMock.class, mockCallout );

After this call method which perform callout. As we have set mock test callout, apex will not perform callout and will return response from static resource.

Note: MultiStaticResourceCalloutMock helps you test different HTTP callout with different endpoint URL. you can create instance of this class and specify callout response in different static resource for different endpoints and then set this as mock callout in test method.
  • Generating mock response in test by implementing the HttpCalloutMock Interface 
Create a apex class which implements HttpCalloutMock interface. In this interface, you can specify response which will be returned if test method perform callout.

@isTest
global class HTTPMockCallout implements HttpCalloutMock {
    global HTTPResponse respond(HTTPRequest req) {
        // specify the response here
        // return response.
    }

Note:
       1. Class should be public or global which implements HttpCalloutMock
       2. You can use @IsTest on this class as this will be used only through test class. In this way it                   will not count against organization code size limit.

Now you can set mock response in test method before calling method which perform HTTP callout.

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

Below is sample code to provide code coverage to "CalloutUtility" apex class using both approaches mentioned above

public class CalloutUtility {
//method to retrieve information about the Salesforce version
public static HttpResponse performCallout() {
HttpRequest req = new HttpRequest();
req.setHeader('Authorization', 'Bearer ' + UserInfo.getSessionID());
req.setHeader('Content-Type', 'application/json');
String domainUrl=URL.getSalesforceBaseUrl().toExternalForm();
system.debug('********domainUrl:'+domainUrl);
req.setEndpoint(domainUrl+'/services/data/');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
system.debug(res.getBody());
return res;
}
}
view rawCalloutUtility.cls hosted with ❤ by GitHub
@isTest
private class CalloutUtilityTest1 {
testMethod static void unittest1() {
StaticResourceCalloutMock mockCallout = new StaticResourceCalloutMock();
mockCallout.setStaticResource('StaticResourceForCallout');
mockCallout.setStatusCode(200);
mockCallout.setHeader('Content-Type', 'application/json');
// Set the mock callout mode
Test.setMock(HttpCalloutMock.class, mockCallout);
// Call the method that performs the callout
HTTPResponse res = CalloutUtility.performCallout();
System.assertEquals(200,res.getStatusCode());
System.assertEquals('application/json', res.getHeader('Content-Type'));
}
}
@isTest
private class CalloutUtilityTest2 {
testMethod static void testCallout() {
// Set mock callout class
Test.setMock(HttpCalloutMock.class, new HTTPMockCallout());
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutUtility.performCallout();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
System.assertEquals(200, res.getStatusCode());
}
}
view rawCalloutUtilityTest2 hosted with ❤ by GitHub
@isTest
global class HTTPMockCallout implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest req) {
HttpResponse res = new HttpResponse();
res.setHeader('Content-Type', 'application/json');
string jsonResBody = '{ "label": "Spring \'17", "url": "/services/data/v39.0","version": "39.0"}';
res.setBody(jsonResBody);
res.setStatusCode(200);
return res;
}
}
view rawHTTPMockCallout.cls hosted with ❤ by GitHub

No comments:

Post a Comment