UnitTest JSONObject显示为null

时间:2015-11-08 16:03:07

标签: android json unit-testing

我遇到了与JSONObject相关的问题。

@Test
public void toUrlTest() throws JSONException {
    String url;

    JSONObject json = new JSONObject();

    json.put"id", 1);
    json.put("email", "test@hotmail.com");
    url = JSONParser.toURLString(json);

    assertEquals("id=1&email=test@hotmail.com", url);

}

问题是当我调试此测试时,它显示没有任何内容放到json对象上。

  

json = {org.json.JSONObject@826}" null"

我检查了一切,我不知道为什么会发生这种情况。 JSONObject在app中运行良好。它只在测试时发生。

PS。 我在build.gradle中添加了这个

 testOptions {
        unitTests.returnDefaultValues = true
        } 

2 个答案:

答案 0 :(得分:6)

Android中有两种类型的单元测试:

  • 已检测(速度慢,您需要设备或模拟器)
  • 非检测或本地(快速,您可以在计算机上的JVM上执行它们)

如果您的单元测试使用Android SDK提供的类(如JSONObject或Context),您必须在以下选项之间进行选择:

  • 使您的测试成为仪器化测试

OR

您在this帖子中提供了有关此主题的更多有用信息。

顺便说一句,在帖子中你将学习一个技巧,将你的JSONObject单元测试转换为你可以在你的本地JVM上执行的非检测测试(没有Roboelectric)

答案 1 :(得分:2)

您可以使用Mockito来模拟JSONObject并返回所需的JSON对象。

示例:

@Test  
public void myTest(){

      JsonHttpResponseHandler handler = myClassUnderTest.getHandlerForGetCalendar(testFuture);
      JSONObject successResp = Mockito.mock(JSONObject.class);
      JSONArray events = Mockito.mock(JSONArray.class);
      JSONObject event = Mockito.mock(JSONObject.class);

  try{
    doReturn("Standup meeting with team..")
    .when(event).getString("Subject");

    doReturn("id_")
    .when(event).getString("Id");

    doReturn(1)
    .when(events).length();

    doReturn(event)
    .when(events).getJSONObject(0);

    doReturn(events)
    .when(successResp).getJSONArray("value");

    handler.onSuccess(200, null, successResp);

  }catch(Exception xx){
    JSONObject errorResp = null;
    try{
      errorResp = new JSONObject("{}"); // this will be null but it's fine for the error case..
    }catch(JSONException ex){
      throw new IllegalStateException("Test Exception during json error response construction. Cause: "+ex);
    }
    handler.onFailure(500, null, new IllegalStateException("Something went wrong in test helper handlerForGetCalendarOnSuccess. Cause: "+xx), errorResp);
  }

  // Assertions you need ..

}