0

I'm trying to use a json in an AndroidTestCase, however the JSONObject is always empty, even though I put an element in it. Do I have to do anything special in order to make JSONObjects work in a unit test?

Here's my AndroidTestCase class:

public class JSONUtilTest extends AndroidTestCase {

    private JSONObject mJSONSummary;

    @Override
    public void setUp() throws Exception {
        super.setUp();
        mJSONSummary = new JSONObject();
        mJSONSummary.put("test", 123);
        assertTrue(mJSONSummary.length() == 1); //assertion error
    }
}

My module's build.grade:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "com.nubank.brunodea"
        minSdkVersion 8
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
        testApplicationId "com.nubank.brunodea"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
    testOptions {
        unitTests.returnDefaultValues = true
    }
}

dependencies {
    compile fileTree(include: ['*.jar'], dir: 'libs')
    compile 'com.android.support:design:22.2.0'
    compile 'com.android.support:support-v4:22.2.0'
    compile 'com.android.support:appcompat-v7:22.2.0'
    testCompile 'junit:junit:4.12'
    compile 'com.android.support:recyclerview-v7:22.2.0'
}

I'm using Android Studio 1.2.2 and when I don't use JSONObjects the tests work.

Thanks!

brunodea
  • 220
  • 1
  • 10

1 Answers1

1

As you already mentioned JSONObject is only mocked so testing this with the default config does not work. You can either choose to use an external JSON implementation for testing like json simple or choose to use another framework which mocks the equivalent classes for you with full functionality like Robolectric can do.

I personally choose the 2nd option but you should consider that this is a very massive testing environment which might be a bit too oversized for simple JSONObject testing.

See also this answer on stackoverflow: https://stackoverflow.com/a/3972592/4310905

Community
  • 1
  • 1
and_dev
  • 3,723
  • 1
  • 20
  • 28