【发布时间】: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