Hello As we know that for Web Service call out we need to call Apex class method as per our requirement .By default, test methods don’t support web service callouts, and tests that perform web service callouts fail.
Due failour test coverage will down and so built-in WebServiceMock interface help to resolve the failure and Test.setMock method helps to increase the test coverage.
When testing these methods, you can instruct the Apex runtime to generate a fake response whenever WebServiceCallout.invoke is called. To do so, implement the WebServiceMock interface and specify a fake response for the Apex runtime to send
Steps to Write Test Class:-
- You can annotate this class with @isTest because it is used only in a test context. In this way, you can exclude it from your org’s code size limit of 6 MB.
- The class implementing the WebServiceMock interface can be either global or public.
NOTE:
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.
HTTPCallout Class:
public class CarLocator {
public static String getCarNameById(Integer id) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
request.setMethod('GET');
HttpResponse response = http.send(request);
String strResp = '';
if (response.getStatusCode() == 200) {
Map < String, Object > results = (Map < String, Object >) JSON.deserializeUntyped(response.getBody());
Map < string, Object > cars = (Map < String, Object >) results.get('car');
strResp = string.valueof(cars.get('name'));
}
return strResp ;
}
}
HTTP Mock Callout Class:
@isTest
global class CarLocatorMock implements HttpCalloutMock {
global HTTPResponse respond(HTTPRequest request) {
HttpResponse response = new HttpResponse();
response.setHeader('Content-Type', 'application/json');
response.setBody('{"car": {"id":2, "name":"Test"}}');
response.setStatusCode(200);
return response;
}
}
Test Class:
@isTest
private class CarLocatorTest {
static testMethod void testPostCallout() {
Test.setMock(HttpCalloutMock.class, new CarLocatorMock ());
String strResp = CarLocator getCarNameById(2);
}
}