2015-10-23 57 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 
} 
相關問題