Skip to main content

I have attched my Remote site setting. 

 

 

public class AnimalLocator { 

 

    public class Animal { 

 

        public Integer id; 

 

        public String name; 

 

        public String eats; 

 

        public String says; 

 

    } 

 

    public class AnimalResult { 

 

        public Animal animal; 

 

    } 

 

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

; 

 

   } 

 

} 

 

************************************************************ 

mock test- 

 

@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":"chicken","eats":"chicken food","says":"cluck cluck"},{"id":2,"name":"duck","eats":"worms","says":"pek pek"}]}'); 

 

        response.setStatusCode(200); 

 

        return response;  

 

    } 

 

} 

*************************************************************** 

Animal locator Test- 

 

@isTest 

 

private 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 response = AnimalLocator.getAnimalNameById(1); 

 

    system.debug('Test Response1--->'+response); 

 

    String expectedValue = 'chicken'; 

 

    System.assertEquals(expectedValue,response); 

 

    String response2 = AnimalLocator.getAnimalNameById(2); 

 

    system.debug('Test Response2--->'+response2); 

 

    String expectedValue2 = 'duck'; 

 

    System.assertEquals(expectedValue2,response2); 

 

} 

 

} 

 

#Trailhead Challenges

1 respuesta
  1. 15 ago 2025, 18:53

    Hi @Abhijeet Gaikwad I’m a member of the Trailhead Help team. If your issue has been resolved, please mark the most helpful response above as the best answer, or share the solution that worked for you and mark it accordingly. If the issue remains unresolved, kindly log a case here for further assistance. Thank you!

0/9000