Apex REST Callouts - 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.
AnimalLocator.apxc
public class AnimalLocator {
public static String getAnimalNameById(Integer animalId ){
String animalName;
Http http = new Http();
HttpRequest request = new HttpRequest();
request.setEndpoint( 'https://th-apex-http-callout.herokuapp.com/animals/'+animalId);
request.setMethod('GET');
HttpResponse response = http.send(request);
if(response.getStatusCode()==200){
Map<String,Object> r = (Map<String, Object>)JSON.deserializeUntyped(response.getBody());
Map<String,Object> animal = (Map<String, Object>)r.get('animal');
animalName = string.valueOf(animal.get('name'));
System.debug('The animal is: '+ animalName);
}
return animalName;
}
}
AnimalLocatorMock.apx@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":"chicken","eats":"chicken food","says":"cluck cluck"}}');
response.setStatusCode(200);
return response;
}
}
AnimalLocatorTest.apxc@isTest
private class AnimalLocatorTest {
@isTest static void getAnimalNameByIdTest(){
//Set mock callout class
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
String response = AnimalLocator.getAnimalNameById(1);
System.assertEquals('chicken', response);
}
}
Comments
Post a Comment