function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Jefferson FernandezJefferson Fernandez 

Trailhead: Apex REST Callout - Create an Apex class that calls a REST endpoint and write a test class

Hi All,

May I ask some help because of this error

"Challenge Not yet complete... here's what's wrong: 
Executing the 'getAnimalNameById' method on 'AnimalLocator' failed. Make sure the method exists with the name 'getAnimalNameById', is public and static, accepts an Integer and returns a String."

All classes were saved without errors. Here are my codes:

<---AnimalLocator class--->
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);
        
        String strRes = '';
        System.debug('response code: ' + response.getStatusCode());
        System.debug('reseponse body: ' + response.getBody());
        
        //If the response is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            Map<String, Object> animals = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        
        //Cast the value in the animals' key as list.
       // List<Object> animals = (List<Object>) results.get('animal');
        System.debug('received the following: ' + animals);
        strRes = String.valueOf(animals.get('name'));
        System.debug('strRes: ' + strRes);
        }   // end if
        
        return strRes;
    }   // end method
}   // end classpublic 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);
        
        String strRes = '';
        System.debug('response code: ' + response.getStatusCode());
        System.debug('reseponse body: ' + response.getBody());
        
        //If the response is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            Map<String, Object> animals = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
        
        //Cast the value in the animals' key as list.
       // List<Object> animals = (List<Object>) results.get('animal');
        System.debug('received the following: ' + animals);
        strRes = String.valueOf(animals.get('name'));
        System.debug('strRes: ' + strRes);
        }   // end if
        
        return strRes;
    }   // end method
}   // end class

<---AnimalLocatorMock--->
@isTest
global class AnimalLocatorMock implements HttpCalloutMock  {
    
    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":"dog","eats":"meat","says":"arf arf!"}}');
        response.setStatusCode(200);
        return response;
        
    }   // end method
}   // end class@isTest
global class AnimalLocatorMock implements HttpCalloutMock  {
    
    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":"dog","eats":"meat","says":"arf arf!"}}');
        response.setStatusCode(200);
        return response;
        
    }   // end method
}   // end class


<----AnimalLocatorTest----->
@isTest
public class AnimalLocatorTest  {
    
    @isTest static void testGetCallout() {
        //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 result = AnimalLocator.getAnimalNameById(1);
        String expectedResult='dog';
        System.assertEquals(result, expectedResult);

    }   // end method
    
}   // end class {@isTest
public class AnimalLocatorTest  {
    
    @isTest static void testGetCallout() {
        //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 result = AnimalLocator.getAnimalNameById(1);
        String expectedResult='dog';
        System.assertEquals(result, expectedResult);

    }   // end method
    
}   // end class {
 
Best Answer chosen by Jefferson Fernandez
Dilip_VDilip_V
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);
          String strResp = '';
           system.debug('******response '+response.getStatusCode());
           system.debug('******response '+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 ;
   }
}

Sorry I didnt shared the main class.

Thanks.

All Answers

Jefferson FernandezJefferson Fernandez
Sorry, the pasted codes were duplicated, i'm not sure what's the problem with AsideIO. I hope you can read my codes.
Dilip_VDilip_V
Jefferson,

Try this class once
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('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
     global HTTPResponse respond1(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(201);
        return response; 
    }
}
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('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(200);
        return response; 
    }
     global HTTPResponse respond1(HTTPRequest request) {
        // Create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animals": ["majestic badger", "fluffy bunny", "scary bear", "chicken", "mighty moose"]}');
        response.setStatusCode(201);
        return response; 
    }
}
AnimalLocatorTest
 
@isTest
private class AnimalLocatorTest{
    @isTest static  void AnimalLocatorMock1() {
        Test.SetMock(HttpCallOutMock.class, new AnimalLocatorMock());
        string result=AnimalLocator.getAnimalNameById(3);
        string expectedResult='chicken';
        System.assertEquals(result, expectedResult);
    }
       @isTest static  void AnimalLocatorMock2() {
        Test.SetMock(HttpCallOutMock.class, new AnimalLocatorMock2());
        string result=AnimalLocator.getAnimalNameById(3);
        string expectedResult='chicken';
        //System.assertEquals(result, expectedResult);
    }
}



Let me know if you have any issues.

Mark it as best answer if it works..

Thanks.
Dilip_VDilip_V
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);
          String strResp = '';
           system.debug('******response '+response.getStatusCode());
           system.debug('******response '+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 ;
   }
}

Sorry I didnt shared the main class.

Thanks.
This was selected as the best answer
Jefferson FernandezJefferson Fernandez
I was able to get idea from your code. Thanks, here are my codes though.
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);
        
        String strRes = '';
        
        //If the response is successful, parse the JSON response.
        if (response.getStatusCode() == 200) {
            System.debug(response.getBody());
            Map<String, Object> animal = (Map<String, Object>) JSON.deserializeUntyped(response.getBody());
            Map<String, Object> animalInfo= (Map<String, Object>) animal.get('animal');
            System.debug(animalInfo);
            Object myAnimal = (Object) animalInfo.get('name');
            System.debug(myAnimal);
            strres = (String) myAnimal;
        }   // end if
        System.debug(strRes);
        return strRes;
    }   // end method
}   // end class
 
@isTest
global class AnimalLocatorMock implements HttpCalloutMock  {
    
    global HttpResponse respond(HttpRequest request) {
        // create a fake response
        HttpResponse response = new HttpResponse();
        response.setHeader('Content-Type', 'application/json');
        response.setBody('{"animal":{"id":2,"name":"bear","eats":"berries, campers, adam seligman","says":"yum yum"}}');
        response.setStatusCode(200);
        return response;
        
    }   // end method
}   // end class
 
@isTest
public class AnimalLocatorTest  {
    
    @isTest static void testGetCallout() {
        //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 result = AnimalLocator.getAnimalNameById(2);
       // String expectedValue = '{"animal":{"id":2,"name":"bear","eats":"berries, campers, adam seligman","says":"yum yum"}}'
        String expectedResult='bear';
        System.assertEquals(result, expectedResult);

    }   // end method
    
}   // end class

 
gil shanigil shani
what is the meaning of the number after the "id" in 
response.setBody('{"animal":{"id":2,"name":"bear","eats":"berries, campers, adam seligman","says":"yum yum"}}');?