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