Skip to content

Instantly share code, notes, and snippets.

@burlistic
Created December 6, 2023 02:48
Show Gist options
  • Save burlistic/edbbb7821dac9ace529d610646471769 to your computer and use it in GitHub Desktop.
Save burlistic/edbbb7821dac9ace529d610646471769 to your computer and use it in GitHub Desktop.
APEX Rest with Mock Animal locator
public class AnimalLocator {
public static String getAnimalNameById(Integer i){
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/' + i);
request.setMethod('GET');
HttpResponse response = http.send(request);
// If the request is successful, parse the JSON response.
if(response.getStatusCode() == 200) {
// Deserializes the JSON string into collections of primitive data types.
Map<String, Object> result = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
Map<String, Object> animal = (Map<String, Object>) result.get('animal');
System.debug('Received the following animal name:');
System.debug(string.valueOf(animal.get('name')));
return string.valueOf(animal.get('name'));
}
return null;
}
}
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest request) {
// Create a fake response
HttpResponse response = new HttpResponse();
response.setHeader('Content-Type', 'application/json');
response.setBody('{"animal": {"id":1,"name": "moose", "eats":"plants","says":"bellows"}}');
response.setStatusCode(200);
return response;
}
}
@isTest
public class AnimalLocatorTest {
@isTest static void testGetAnimalNameById() {
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
String result = AnimalLocator.getAnimalNameById(1);
System.assertEquals('moose', result);
}
@isTest static void testGetAnimalNameById500() {
StaticResourceCalloutMock mock = new StaticResourceCalloutMock();
mock.setStaticResource('GetAnimalResource');
// Set a failed request code - content can be ignored
mock.setStatusCode(500);
// Associate the callout with a mock response
Test.setMock(HttpCalloutMock.class, mock);
String result = AnimalLocator.getAnimalNameById(1);
System.assertEquals(null, result);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment