【问题标题】:Mocking response for HTTPGet in JavaJava中HTTPGet的模拟响应
【发布时间】:2017-06-21 05:39:03
【问题描述】:

我必须模拟对返回 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(),如示例中所示,因为该方法不存在。

【问题讨论】:

    标签: java junit mockito httpentity


    【解决方案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());
    

    【讨论】:

      猜你喜欢
      • 2018-11-28
      • 2022-01-15
      • 1970-01-01
      • 2013-01-23
      • 1970-01-01
      • 2014-10-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多