I´m trying to complete a trailhead challenge but when I test the method, it appears the error
System.JSONException: Unexpected character ('a' (code 97)): was expecting double-quote to start field name at [line:1, column:3]
This is the json
{"animal":{"id":0,"name":"","eats":"","says":""}}
Also, when I run the same code on Execute Anonymous, it does work! So I don't know what else to do.
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);
Map<String,Object> result = (Map<String,Object>)JSON.deserializeUntyped(response.getBody());
Map<String,Object> animal = (Map<String,Object>) result.get('animal');
return (String)animal.get('name');
}
}
@isTest
public class AnimalLocatorTest {
@isTest static void testAnimalLocator(){
Test.setMock(HttpCalloutMock.class, new AnimalLocatorMock());
String name = AnimalLocator.getAnimalNameById(0);
System.assertEquals(name, 'Alex');
}
}
The error seems to be here Map<String,Object> animal = (Map<String,Object>) result.get('animal');
UPDATE The error was in the CalloutMock class, I was trying to create a JSON without the double quotes.
public HttpResponse respond(HttpRequest request){
HttpResponse response = new HttpResponse();
response.setBody('{"animal": {"id": 0, "name": "Alex", "eats": "", "says": ""}}');
response.setStatusCode(200);
return response;
}