我有以下Test类,我需要使用OKhttp从API中的json中检索信息(如果没有办法用OKHttp执行此操作,还有其他推荐的方法吗?),但它不是工作我在openRestaurants != null
:
@Config(constants = HomeActivity.class, sdk= 16, manifest = "src/main/AndroidManifest.xml")
@RunWith(RobolectricTestRunner.class)
public class RestaurantFindTest{
private String jsonData = null;
private JSONObject jsonResponse;
private JSONArray openRestaurants;
String url = "http://example/api/find/restaurants";
@Before
public void setUp() throws Exception {
OkHttpClient client = new OkHttpClient();
Request request = new Request.Builder()
.url(url)
.build();
Call call = client.newCall(request);
Response response = null;
try {
response = call.execute();
if (response.isSuccessful()) {
jsonData = response.body().string();
} else {
jsonData = null;
jsonResponse = new JSONObject(jsonData);
openRestaurants = jsonResponse.getJSONArray("open");
}
} catch (IOException e) {
e.printStackTrace();
}
}
@Test
public void testGetOpenRestaurants() throws Exception {
assertTrue(openRestaurants != null);
}
}
答案 0 :(得分:0)
jsonData = null;
jsonResponse = new JSONObject(jsonData);
openRestaurants = jsonResponse.getJSONArray("open");
您创建一个新的JSONObject传入null作为构造函数参数
=>它将是空的= => jsonResponse.getJSONArray("open");
将失败。
你可能想要这样的东西:
if (response.isSuccessful()) {
jsonData = response.body().string();
jsonResponse = new JSONObject(jsonData);
openRestaurants = jsonResponse.getJSONArray("open");
} else {
// handle failure
}