Skip to content

Instantly share code, notes, and snippets.

@tvaidyan
Created May 20, 2021 10:55
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tvaidyan/c72aa714ead90cb09a6e8e9811ee771c to your computer and use it in GitHub Desktop.
Save tvaidyan/c72aa714ead90cb09a6e8e9811ee771c to your computer and use it in GitHub Desktop.
Salesforce Trailhead > APEX Integration Services > Apex REST Callouts
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 animalName = null;
// If the request is successful, parse the JSON response.
if (response.getStatusCode() == 200) {
// Deserialize into an animal
JSON2Apex j = (JSON2Apex) JSON2Apex.parse(response.getBody());
animalName = j.Animal.name;
}
return animalName;
}
}
@isTest
global class AnimalLocatorMock implements HttpCalloutMock {
// Implement this interface method
global HTTPResponse respond(HTTPRequest request) {
// Create a fake response
HttpResponse response = new HttpResponse();
response.setBody('{"animal":{"id":1,"name":"chicken","eats":"chicken food","says":"cluck cluck"}}');
response.setStatusCode(200);
return response;
}
}
@isTest
public class AnimalLocatorTest {
@isTest
public static void testGetAnimalNameById() {
AnimalLocatorMock mock = new AnimalLocatorMock();
// Associate the callout with a mock response
Test.setMock(HttpCalloutMock.class, mock);
// Call method to test
String animalName = AnimalLocator.getAnimalNameById(1);
// Verify we got a chicken
System.assertEquals('chicken', animalName,
'The name of the test animal should be a chicken.');
}
}
public class JSON2Apex {
public Animal animal;
public class Animal {
public Integer id;
public String name;
public String eats;
public String says;
}
public static JSON2Apex parse(String json) {
return (JSON2Apex) System.JSON.deserialize(json, JSON2Apex.class);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment