简体   繁体   中英

AndroidStudio: when I try to initialize a JSONObject in Unit test class it always outputs null

I am trying to create a unit test for a class that uses json object.

This is the class I

    public JsonDataModel(String name, String tag, String color, double price) throws JSONException {
            this.name = name;
            this.tag = tag;
            this.color = color;
            this.price = price;
            initializeObject();
        }

  

     private void initializeObject() throws JSONException {
            object.put("Name", name);
            object.put("Tag", tag);
            object.put("Color", color);
            object.put("Price", price);
        }

This is the unit test setup:

    private JsonDataModel model;

    @BeforeEach
    void setUp() throws JSONException {
        
        model = new JsonDataModel("testName", "testTag", "testColor", 10);

    }

Once I run the test and setUp() is done, I checked the object inside model and it shows null . The weird thing is that if I try to run the app and look with the debugger at the objects created in JsonDataModel , the json object is generated correctly. It looks like when I try to initialize a JSONObject in the unit file test, it always outputs null . Does anyone have any idea what is the problem?

I think that the problem is with the initializeObject function, it saves some data inside "object", but that "object" came from no where. I don't see it anywhere inside the constructor, as if he's null when he reaches back to the Unit Test.

try to initialize this object before "putting" things inside it.

turns out the problem is that the line testImplementation 'org.json:json:20140107' is missing in build.gradle(app) in the dependencies

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM