Why is my JSONObject related unit test failing?

▼魔方 西西 提交于 2019-11-28 08:54:11
Lucas L.

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

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:20180130'
}

Alternatively, you can download and include the jar:

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

It is not known which version of the maven artifact corresponds exactly/most closely to what ships with Android.

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!