【问题标题】:UnitTest JSONObject shows nullUnitTest JSONObject 显示为空
【发布时间】:2015-11-08 16:03:07
【问题描述】:

我遇到了与 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 在应用程序中工作正常。它只会在测试时发生。

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

 testOptions {
        unitTests.returnDefaultValues = true
        } 

【问题讨论】:

  • 你在哪里运行测试?在 PC 上还是在设备/模拟器上?
  • 我猜我用的是电脑,因为没有屏幕可以选择设备
  • 此类测试不适用于带有 android.jar 的 PC。 android.jar 仅包含类的签名,而不包含实现。在设备上运行测试。
  • 是否需要 build.gradle 中的其他设置?你有一些关于如何做到这一点的提示吗?我是安卓新手

标签: android json unit-testing


【解决方案1】:

TL;Yair Kukielka 回应的 DR 版本...(谢谢!)

按照

的建议,将此添加到您的 build.gradle 文件中
testImplementation "org.json:json:20140107"

这会将存根的 Android 库替换为可在桌面上运行的库。

【讨论】:

  • 又好又简单的解决方案
【解决方案2】:

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

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

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

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

您可以在this 帖子中获得有关此主题的更多有用信息。

顺便说一下,在这篇文章中,您将学习将 JSONObject 单元测试转换为可以在本地 JVM(没有 Roboelectric)上执行的非仪器测试的技巧

【讨论】:

  • Post 非常适合将 json 与本地 JVM 一起用于测试目的!
【解决方案3】:

您可以使用 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 ..

}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-11-04
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2016-06-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多