Tuesday, November 8, 2022

Testing HTTP Callouts by Implementing the HttpCalloutMock Interface in Salesforce


This is a full example that shows how to test an HTTP callout. 

CalloutClass

====================

public class CalloutClass {
public static HttpResponse getInfoFromExternalService() {
HttpRequest req = new HttpRequest();
req.setEndpoint('https://example.com/example/test');
req.setMethod('GET');
Http h = new Http();
HttpResponse res = h.send(req);
return res;
}
}


JSON2ApexMock Apex Class

==============================

 @isTest

global class JSON2ApexMock implements HttpCalloutMock {

HttpResponse res;
global JSON2ApexMock(HttpResponse r)
{
res=r;
}
global HttpResponse respond(HttpRequest req){
return res;
}
}


Callout Test Class
=====================================
@isTest
private class CalloutClassTest {
@isTest static void testCallout() {

// Create a fake response
HttpResponse res=new HttpResponse();
res.setBody('{"Description": "200"}');
res.setHeader('Content-Type', 'application/json;charset=UTF-8');
res.setStatusCode(200);

// Set mock callout class
Test.setMock(HttpCalloutMock.class, new JSON2ApexMock(res));
// Call method to test.
// This causes a fake response to be sent
// from the class that implements HttpCalloutMock.
HttpResponse res = CalloutClass.getInfoFromExternalService();
// Verify response received contains fake values
String contentType = res.getHeader('Content-Type');
System.assert(contentType == 'application/json');
String actualValue = res.getBody();
String expectedValue = '{"Description":"200"}';
System.assertEquals(actualValue, expectedValue);
System.assertEquals(200, res.getStatusCode());
}
}


If you have any comments or queries about this, please feel free to mention them in the comments section below.

No comments:

Post a Comment