Learnify_Rectify

Apex REST Callouts(2nd task)

Jun 24th, 2024
9,077
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 2.06 KB | Source Code | 0 0
  1. Apex REST Callouts from (module - Apex Integration Services)
  2.  
  3. -------------------------------------------------
  4. SOURCE CODE: AnimalLocator
  5.  
  6. public class AnimalLocator {
  7. public static String getAnimalNameById (Integer id) {
  8. String AnimalName = '';
  9. Http http = new Http();
  10. HttpRequest request = new HttpRequest();
  11. request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
  12. request.setMethod('GET');
  13. HttpResponse response = http.send(request);
  14. if (response.getStatusCode() == 200) {
  15. Map<String,Object> results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
  16. Map<String, Object> animal = (Map<String, Object>) results.get('animal');
  17. animalName = (String) animal.get('name');
  18. }
  19. return animalName;
  20. } }
  21.  
  22. -------------------------------------------------
  23. SOURCE CODE: AnimalLocatorTest
  24.  
  25. @isTest
  26. private class AnimalLocatorTest {
  27. @isTest static void testGet() {
  28. Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
  29. // Call method to test
  30. String result = AnimalLocator.getAnimalNameById (7);
  31. // Verify mock response is not null
  32. System.assertNotEquals(null,result,
  33. 'The callout returned a null response.');
  34. System.assertEquals('dog', result,
  35. 'The animal name should be \'dog\'');
  36. } }
  37.  
  38. -------------------------------------------------
  39. SOURCE CODE: AnimalLocatorMock
  40.  
  41. @isTest
  42. global class AnimalLocatorMock implements HttpCalloutMock{
  43.  
  44. // Implement this interface method
  45. global HTTPResponse respond(HTTPRequest request) {
  46. // Create a fake response
  47. HttpResponse response = new HttpResponse();
  48. response.setHeader('Content-Type', 'application/json');
  49. response.setBody('{"animal":{"id":7,"name":"dog","eats":"meat","says":"i am a lovely pet animal"}}');
  50. response.setStatusCode(200);
  51. return response;
  52. } }
  53.  
  54.  
  55.  
  56.  
Add Comment
Please, Sign In to add comment