Skip to content

Instantly share code, notes, and snippets.

@mannharleen
Created October 31, 2016 15:36
Show Gist options
  • Save mannharleen/2890d40f5cea62d058d62f7c16e39f73 to your computer and use it in GitHub Desktop.
Save mannharleen/2890d40f5cea62d058d62f7c16e39f73 to your computer and use it in GitHub Desktop.
Salesforce trailhead - Apex-Integration-Services-Apex-REST-Callouts
public class AnimalLocator {
public class cls_animal {
public Integer id;
public String name;
public String eats;
public String says;
}
public class JSONOutput{
public cls_animal animal;
//public JSONOutput parse(String json){
//return (JSONOutput) System.JSON.deserialize(json, JSONOutput.class);
//}
}
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.setHeader('id', String.valueof(id)); -- cannot be used in this challenge :)
request.setMethod('GET');
HttpResponse response = http.send(request);
system.debug('response: ' + response.getBody());
//Map<String,Object> map_results = (Map<String,Object>) JSON.deserializeUntyped(response.getBody());
jsonOutput results = (jsonOutput) JSON.deserialize(response.getBody(), jsonOutput.class);
//Object results = (Object) map_results.get('animal');
system.debug('results= ' + results.animal.name);
return(results.animal.name);
}
}
@IsTest
global class AnimalLocatorMock implements HttpCalloutMock {
global HTTPresponse respond(HTTPrequest request) {
Httpresponse response = new Httpresponse();
response.setStatusCode(200);
//-- directly output the JSON, instead of creating a logic
//response.setHeader('key, value)
//Integer id = Integer.valueof(request.getHeader('id'));
//Integer id = 1;
//List<String> lst_body = new List<String> {'majestic badger', 'fluffy bunny'};
//system.debug('animal return value: ' + lst_body[id]);
response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
return response;
}
}
@IsTest
public class AnimalLocatorTest {
@isTest
public static void testAnimalLocator() {
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
//Httpresponse response = AnimalLocator.getAnimalNameById(1);
String s = AnimalLocator.getAnimalNameById(1);
system.debug('string returned: ' + s);
}
}
@krzysztof-krzeszewski
Copy link

Also it seems that the challenge misreported the coverage as being under 100%, because I had tests for other apex classes unrelated to the challenge that were not 100% covered.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment