Friday, May 27, 2016

APEX: HTTP Callouts Testing using HttpCalloutMock

So far, we have seen a simple way for testing REST services in a single test method http://programmersrealm.blogspot.com/2016/05/creating-tests-for-rest-services-in.html

However, there may be times when we don't want to hit the actual server. Isolating our testing in our environment is ideal and crucial to catch any errors before testing in the real environment.

As a best practice, we can use the HttpCalloutMock Interface that Salesforce provides out of the box.
This will help us provide fake responses in our test class.

1. Implement the HttpCalloutMock

@isTest
global class MyHttpCalloutMock implements HttpCalloutMock
{
    // Need to override this method
    global HTTPResponse respond(HTTPRequest req)
    {
        try
        {
           HttpResponse res = new HttpResponse();
           res.setHeader('Content-Type', 'application/json');
           res.setBody('{"myvar":"myvalue"}');
           res.setStatusCode(200);
        }
        catch(Exception ex)
        {
           system.debug(ex.getMessage() + ' ' + ex.getStackTraceString());
        }
        return res;
     }
}


2. Create the test class
@isTest
public class RestServiceTest 
{
     public static testMethod void testRestGetService() 
     {
        try
        {
           Test.startTest();
             Test.setMock(HttpCalloutMock.class, new MyHttpCalloutMock());
        
             HttpResponse res = MyCalloutClass.processGetService();
        
             // provide your assertions here

           Test.stopTest();
        }
        catch(Exception ex)
        {
           system.debug(ex.getMessage() + ' ' + ex.getStackTraceString());
        }
    }
}
This is the sample Callout Class public class MyCalloutClass { public static HttpResponse processGetService() { try { HttpRequest req = new HttpRequest(); req.setEndpoint('http://yourendpoint/myvar/myvalue'); req.setMethod('GET'); Http h = new Http(); HttpResponse res = h.send(req); } catch(Exception ex) { system.debug(ex.getMessage() + ' ' + ex.getStackTraceString()); } return res; } }

You can find more information to the original article here: https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_classes_restful_http_testing_httpcalloutmock.htm

No comments:

Post a Comment