Android UnitTest JSONObject显示空值

Android UnitTest JSONObject显示空值,android,json,unit-testing,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); assert

我遇到了一个与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}“空”

我检查了所有东西,不知道为什么会发生这种事。JSONObject在应用程序中运行良好。它只在测试时发生

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

 testOptions {
        unitTests.returnDefaultValues = true
        } 

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

  • 插入指令的(速度慢,需要设备或模拟器)
  • 非仪器化或本地(快速,您可以在计算机上的JVM上执行)
如果您的单元测试使用Android SDK提供的类(如JSONObject或a),那么您必须在以下两者之间进行选择:

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

  • 使用
在这篇文章中你有更多关于这个主题的有用信息


顺便说一句,在本文中,您将学习一个技巧,将JSONObject单元测试转换为非仪器化测试,您可以在本地JVM上执行(无Roboelectric)

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

}TL;Yair Kukielka回应的博士版本。。。(谢谢!)

按照建议,将其添加到
build.gradle
文件中

testImplementation "org.json:json:20140107"

这将用在桌面上工作的Android库取代存根库。

您在哪里运行测试?在PC上还是在设备/模拟器上?我想我使用PC,因为没有屏幕可以选择设备。这样的测试在带有android.jar的PC上不起作用
android.jar
只包含类的签名,而不包含实现。在设备上运行测试。build.gradle中是否需要其他设置?你有没有关于如何做这件事的建议?我是androidPost的新手,在本地JVM中使用json只是为了测试目的,这非常棒!好的简单的解决方案