3

Create an Apex class that calls a REST endpoint and write a test class.

To pass this challenge, create an Apex class that calls a REST endpoint to return the name of an animal, write unit tests that achieve 100% code coverage for the class using a mock response, and run your Apex tests.

  • The Apex class must be called 'AnimalLocator', have a 'getAnimalNameById' method that accepts an Integer and returns a String.
  • The 'getAnimalNameById' method must call https://th-apex-http-callout.herokuapp.com/animals/:id, using the ID passed into the method. The method returns the value of the 'name' property (i.e., the animal name).
  • Create a test class named AnimalLocatorTest that uses a mock class called AnimalLocatorMock to mock the callout response.
  • The unit tests must cover all lines of code included in the AnimalLocator class, resulting in 100% code coverage.
  • Run your test class at least once (via 'Run All' tests the Developer Console) before attempting to verify this challenge.

Facing the below issue:: enter image description here

The code I used::

@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":"chicken","eats":"chicken food","says":"cluck cluck"}}');
        response.setStatusCode(200);
        return response;
    }
}

enter image description here

AnimalLocator

public class AnimalLocator {

  public static String getAnimalNameById(Integer id){
        HttpRequest request = new HttpRequest();
        request.setEndpoint('https://th-apex-http-callout.herokuapp.com/animals/'+id);
        request.setMethod('GET');

        Http http = new Http();
        HttpResponse response = http.send(request);
        String strResp = '';
        System.debug('STATUS CODE : '+response.getStatusCode());
        System.debug('response Body : '+response.getBody());


        // 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> results = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());

            // Cast the values in the 'animals' key as a list
           Map<string,object> animals = (map<string,object>) results.get('animal');
           System.debug('Received the following animals:' + animals );
           strResp = string.valueof(animals.get('name'));
           System.debug('strResp >>>>>>' + strResp );
        }
        return strResp ;
   }
}
0

1 Answer 1

8

This is the step by step approach for this implementation.

Animal

public class Animal {
  public Integer id;
  public String name;
  public String eats;
  public String says;
 }

AnimalResult

public class AnimalResult {
  public Animal animal;
}

AnimalLocator

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);
        AnimalResult result = (AnimalResult) JSON.deserialize(response.getBody(), AnimalResult.class);
        return result.animal.name;
   }

}

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": "5", "name": "Tiger",  "eats": "meat", "says": "roar" }}');
    response.setStatusCode(200);
    return response; 
  }
}

AnimalLocatorTest

@isTest
private class AnimalLocatorTest 
{
  @isTest static void testPostCallout() {
    // Set mock callout class 
    Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock()); 
    // This causes a fake response to be sent
    // from the class that implements HttpCalloutMock. 
    String expectedValue = AnimalLocator.getAnimalNameById(1);
        System.debug('expectedValue=' + expectedValue);
    //System.assertNotEquals(0, expectedValue.length());    
  }
}
4
  • From where you bring AnimalResult class? Commented Apr 22, 2017 at 18:55
  • Again whats the use of public Animal animal; ?? Where is the Animal ? Commented Apr 22, 2017 at 19:00
  • I have used the structure, rather than using the Map Commented Apr 22, 2017 at 19:03
  • Thanks for being so quick in answering. Good approach if someone dont want to use Map. It defiantly works. Commented Apr 22, 2017 at 19:08

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .