Balazs Varhegyi Balazs Varhegyi - 1 year ago 228
Java Question

How do I instantiate an unirest HttpResponse<JsonNode> for my mock?

Let's say I have a class called Api and it has a method:

public class Api{
public HttpResponse<JsonNode> request() {
try {
return Unirest.get("http://localhost:8080").header("accept", "application/json").asJson();
} catch (UnirestException e) {
throw new RuntimeException(e);

And I have a class:

public class Dao(){

private Api api;
public Dao(Api api){
this.api = api;

public Integer test(){
Integer result = api.request().getInteger("result");
return result + 100;

In my test I want to test my business logic based on the response my API.request method returns.

Something like:

import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.stub;
import org.json.JSONObject;
import com.mashape.unirest.http.HttpResponse;

public class ApiTest {
private API api = mock(API.class);
public void test() {
HttpResponse<JsonNode> response = null;
JSONObject result = new JSONObject();
Dao dao = new Dao(api);
assertTrue(dao.test() > 100);

How do I instantiate the HttpResponse with a Body "{ number: 10 }" to be able to return it with the mock?

Answer Source

It works with:

import org.apache.http.impl.DefaultHttpResponseFactory;
import org.json.JSONObject;

HttpResponseFactory factory = new DefaultHttpResponseFactory();
org.apache.http.HttpResponse response = factory.newHttpResponse(new BasicStatusLine(HttpVersion.HTTP_1_1, HttpStatus.SC_OK, null), null);
JSONObject json = new JSONObject();
json.put("result", "10");
response.setEntity(new StringEntity(json.toString()));
com.mashape.unirest.http.HttpResponse<JsonNode> httpResponse = new HttpResponse<JsonNode>(response, JsonNode.class);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download