I have the following Test class which I need to retrieve information from a json in an API using OKhttp (if there is no way to do this with OKHttp is there any other recommended way?), but it isn't working I keep failing my test where 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);
}
}
jsonData = null;
jsonResponse = new JSONObject(jsonData);
openRestaurants = jsonResponse.getJSONArray("open");
You create a new JSONObject passing in null as a constructor argument
=> it will be empty
=> jsonResponse.getJSONArray("open");
will fail.
Probably you wanted something like this:
if (response.isSuccessful()) {
jsonData = response.body().string();
jsonResponse = new JSONObject(jsonData);
openRestaurants = jsonResponse.getJSONArray("open");
} else {
// handle failure
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.