Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- Apex REST Callouts from (module - Apex Integration Services)
- -------------------------------------------------
- SOURCE CODE: AnimalLocator
- public class AnimalLocator {
- public static String getAnimalNameById (Integer id) {
- String AnimalName = '';
- 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);
- if (response.getStatusCode() == 200) {
- Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
- Map<String, Object> animal = (Map<String, Object>) results.get('animal');
- animalName = (String) animal.get('name');
- }
- return animalName;
- } }
- -------------------------------------------------
- SOURCE CODE: AnimalLocatorTest
- @isTest
- private class AnimalLocatorTest {
- @isTest static void testGet() {
- Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
- // Call method to test
- String result = AnimalLocator.getAnimalNameById (7);
- // Verify mock response is not null
- System.assertNotEquals(null,result,
- 'The callout returned a null response.');
- System.assertEquals('dog', result,
- 'The animal name should be \'dog\'');
- } }
- -------------------------------------------------
- SOURCE CODE: AnimalLocatorMock
- @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":7,"name":"dog","eats":"meat","says":"i am a lovely pet animal"}}');
- response.setStatusCode(200);
- return response;
- } }
Add Comment
Please, Sign In to add comment