Why is my JSONObject related unit test failing?

前端 未结 3 506
天涯浪人
天涯浪人 2020-12-08 18:34

I\'m running my tests using gradle testFlavorType

JSONObject jsonObject1 = new JSONObject();
JSONObject jsonObject2 = new JSONObject();
jsonObje         


        
相关标签:
3条回答
  • 2020-12-08 18:53

    The class JSONObject is part of the android SDK. That means that is not available for unit testing by default.

    From http://tools.android.com/tech-docs/unit-testing-support

    The android.jar file that is used to run unit tests does not contain any actual code - that is provided by the Android system image on real devices. Instead, all methods throw exceptions (by default). This is to make sure your unit tests only test your code and do not depend on any particular behaviour of the Android platform (that you have not explicitly mocked e.g. using Mockito).

    When you set the test options to

    testOptions {
        unitTests.returnDefaultValues = true
    }
    

    you are fixing the "Method ... not mocked." problem, but the outcome is that when your code uses new JSONObject() you are not using the real method, you are using a mock method that doesn't do anything, it just returns a default value. That's the reason the object is null.

    You can find different ways of solving the problem in this question: Android methods are not mocked when using Mockito

    0 讨论(0)
  • 2020-12-08 19:14

    As Lucas says, JSON is bundled up with the Android SDK, so you are working with a stub.

    The current solution is to pull JSON from Maven Central like this:

    dependencies {
        ...
        testCompile 'org.json:json:20200518'
    }
    

    You can replace the version 20200518 with the the latest one depending on the Android API. It is not known which version of the maven artefact corresponds exactly/most closely to what ships with Android.

    Alternatively, you can download and include the jar:

    dependencies {
        ...
        testCompile files('libs/json.jar')
    }
    

    Note that you also need to use Android Studio 1.1 or higher and at least build tools version 22.0.0 or above for this to work.

    Related issue: #179461

    0 讨论(0)
  • 2020-12-08 19:16

    Well, my first hunch would be that your getMessage() method returns null. You could show the body of that method in your question and have us find the answer for you, but you should probably research how to debug android applications using breakpoints.
    That way you can run your code step by step and see the values of each variable at every step. That would show you your problem in no time, and it's a skill you should definitely master as soon as possible if you intend to get seriously involved in programming.

    0 讨论(0)
提交回复
热议问题