The mock HTTPCallOuts available in Salesforce are below
1. StaticResourceCalloutMock
2. HttpCalloutMock
Test class for HTTPCallouts in Salesforce
Sample HTTPCallout Class:
public class AnimalLocator {
public static String getAnimalNameById(
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 > animals =
(Map < String, Object >) results.get('animal');
strResp = String.valueof(
animals.get(
'name'
)
);
}
return strResp;
}
}
Sample HTTP Mock Callout Class:
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
global HTTPResponse respond(
HTTPRequest request
) {
HttpResponse response = new HttpResponse();
response.setHeader(
'Content-Type',
'application/json'
);
response.setBody(
'{"animal": {"id":2, "name":"Test"}}'
);
response.setStatusCode(
200
);
return response;
}
}
Test Class:
@isTest
private class AnimalLocatorTest {
static testMethod void testPostCallout() {
Test.setMock(
HttpCalloutMock.class,
new AnimalLocatorMock()
);
String strResp =
AnimalLocator.getAnimalNameById(
2
);
}
}