Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

UnitTest JSONObject shows null

I have got a problem connected with JSONObject.

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

    JSONObject json = new JSONObject();

    json.put"id", 1);
    json.put("email", "[email protected]");
    url = JSONParser.toURLString(json);

    assertEquals("id=1&[email protected]", url);

}

The problem is when I am debugging this test, it shows that nothing is put to json object.

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

I checked everything and I got no clue why this happen. JSONObject works fine in app. It only happens while testing.

PS. I have added in build.gradle this

 testOptions {
        unitTests.returnDefaultValues = true
        } 
like image 617
wacik93 Avatar asked Nov 08 '15 16:11

wacik93


2 Answers

TL;DR version of Yair Kukielka's response... (thanks!)

Add this to your build.gradle file, as suggested by

testImplementation "org.json:json:20140107"

This will replace the stubbed Android library with one that works on the desktop.

Edit April '22: Comments suggest that this is the latest version:

testImplementation "org.json:json:20180813"
like image 56
mm2001 Avatar answered Nov 08 '22 03:11

mm2001


There are 2 types of unit tests in Android:

  • Instrumented (slow and you need a device or emulator)
  • Non-instrumented or local (fast and you can execute them on the JVM on your computer)

If your unit tests use classes provided by the Android SDK (like the JSONObject or a Context), you'll have to choose between:

  • making your test an instrumented test

OR

  • use Robolectric

You have more useful info about this subject in this post.

By the way, in the post you'll learn a trick to convert your JSONObject unit test to a non-instrumented test that you can execute on your local JVM (without Roboelectric)

like image 7
Yair Kukielka Avatar answered Nov 08 '22 01:11

Yair Kukielka