在Java中模拟HTTPGet的响应

时间:2017-02-03 18:57:02

标签: java junit mockito httpentity

我必须模拟对API的请求,该API返回带有JSON实体的响应 为此,我模拟了get请求以及JSON对象

public class RestTest {
    static JSONObject job;
    static JSONArray portsArray;
    static JSONArray routesArray;
    static JSONObject routeObject;
    private static final HttpClient  client = mock(DefaultHttpClient.class);
    private static final HttpGet  get = mock(HttpGet.class);
    private static final HttpResponse response = mock(CloseableHttpResponse.class);
    private static  HttpEntity entity = mock(HttpEntity.class);

    @BeforeClass
    public static void setup() throws ClientProtocolException, IOException, JSONException {
        HttpGet getRoute = new HttpGet("api/to/access");
        getRoute.setHeader("Content-type", "application/json");
        JSONObject routesJson = new JSONObject();
        routesJson.put("","");
        when(response.getEntity()).thenReturn(entity);
        when(response.getEntity().getContent().toString()).thenReturn(routesJson.toString());
        when(client.execute(getRoutes)).thenReturn(response);
    }
}

这会在when(response.getEntity().getContent().toString()).thenReturn(routesJson.toString());

返回一个空指针

如何正确模拟JSON对象,以便在执行实际请求时返回模拟的JSON?

我无法设置entity.setContent(),如示例所示,因为该方法不存在。

1 个答案:

答案 0 :(得分:1)

好吧,我们来看看这两行。

    when(response.getEntity()).thenReturn(entity);
    when(response.getEntity().getContent().toString()).thenReturn(routesJson.toString());

您认为哪个优先?我不知道,无论文档说什么,我都不会指望它有明确的定义。

可能发生的事情:

你说

   when(response.getEntity()).thenReturn(entity);

发生这种情况时:

   response.getEntity().getContent().toString()

你可能正在打电话

entity.getContent().toString()

肯定会导致NPE,因为您没有为entity.getContent()

定义任何内容

如果您必须以这种方式进行测试,我建议您使用RETURNS_DEEP_STUBS。所以

 private static final HttpResponse response = mock(CloseableHttpResponse.class, 
Mockito.RETURNS_DEEP_STUBS);

然后,您可以完全跳过手动模拟HttpEntity,然后执行

when(response.getEntity().getContent().toString()).thenReturn(routesJson.toString());