2015-10-23 21 views
0

我有以下测试类,我需要从API中使用OKhttp从一个JSON中检索信息(如果没有办法与OKHttp做这个有没有其他推荐的方法?),但它不工作我保持没有我的测试,其中openRestaurants != null如何在Android中使用带roboelectric或junit的http调用?

@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
jsonData = null; 
jsonResponse = new JSONObject(jsonData); 
openRestaurants = jsonResponse.getJSONArray("open"); 

您创建一个新的JSONObject在空传递构造函数参数
=>这将是空
=>jsonResponse.getJSONArray("open");将失败。

也许你想是这样的:

if (response.isSuccessful()) { 
    jsonData = response.body().string(); 
    jsonResponse = new JSONObject(jsonData); 
    openRestaurants = jsonResponse.getJSONArray("open"); 
} else { 
    // handle failure 
} 
相关问题