To deploy or package Apex, 75% of your code must have test coverage. By default, test methods don’t support HTTP callouts, so tests that perform callouts fail. Enable HTTP callout testing by instructing Apex to generate mock responses in tests, using Test.setMock.
This is a full example that shows how to test an HTTP callout.
Sample HTTPCallout Class:
public class AnimalLocator {
public static String getAnimalNameById(Integer id) {
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('http://example.com/example/test/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":1, "name":"Tiger"}}');
response.setStatusCode(200);
return response;
}
}
Test Class for HTTPCallouts:
@isTest
private class AnimalLocatorTest {
static testMethod void testPostCallout() {
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
String strResp = AnimalLocator.getAnimalNameById(1);
}
}
Done thats it 👍!!!!
No comments:
Post a Comment