1

我必须模拟对返回 JSON 实体响应的 API 的请求为此,我模拟 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()由于该方法不存在,因此我无法按照示例中的方式进行设置。

4

1 回答 1

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());
于 2017-02-03T19:14:36.650 回答