Why is my JSONObject related unit test failing?

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

I\'m running my tests using gradle testFlavorType

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


        
3条回答
  •  旧时难觅i
    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

提交回复
热议问题