Skip to main content
Hello,

I have a question. In the challenge, we're asked to create the 'getAnimalNameById' method that accepts an Integer and returns a String.

The AnimalLocatorMock is NOT returning a string, instead it's returning a HTTPResponse. So, when I actually try to make the callout in the Test Method, I'm getting an error (Illegal assignment from String to System.HttpResponse).

I could change my 'getAnimalNameByID' method to return a HTTPResponse instead of a String. But, is this the correct way or am I missing something? I've pasted the code snippets below.

 

@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;

}

}

 

@isTest

public class AnimalLocatorTest {

@isTest static void testGet(){

//set the mockout class

Test.setMock(HTTPCalloutMock.class, new AnimalLocatorMock());

//Do the callout here

HTTPResponse response = AnimalLocator.getAnimalNameById(1);

}

}

 
3 respostas
  1. 23 de fev. de 2016, 13:38
    Hello,

    You need ti rewrite AnimalLocator.getAnimalNameById method. When you do a callout, it returns HttpResponse, for retrieve string use getBody method.

     

    HttpRequest req = new HttpRequest();

    ...

    Http http = new Http();

    HttpResponse res = http.send(req);

    String response = res.getBody(); // String value

    return response;

    Thanks,

    Alex