首页 > 解决方案 > 在单元测试中使用 JSONObject#toString (Android Studio)

问题描述

我想检查我的一个类是否可以很好地处理 JSON 对象。为此,我决定使用单元测试环境为其提供 JSONObject。但它始终未能提供预期的结果......直到我在测试方法本身中测试了JSONObject的行为。

这是代码:

    @Test
    public void checkJsonObject() {

        JSONObject obj;
        try {

            obj = new JSONObject();
            obj.put("front", "cat");
            obj.put("back", "chat");
            obj.put("bucket", 2);

            System.out.println("Object is " + (obj == null ? "" : "not") + " null");
            System.out.println("JSON content is: " + obj.toString());

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

这些是获得的结果:

Object is not null
JSON content is: null

预期的结果是:

Object is not null
JSON content is: {  "front"     : "cat",
                    "back"      : "chat",
                    "bucket"    : 2
                }

(或类似的)。

因此,JSONObject 不为空。但是 .toString() 方法返回 null。

我在代码中遗漏了什么?

万一很重要,应用程序的依赖项包含:

testImplementation 'junit:junit:4.12'
testImplementation 'androidx.test:core:1.0.0'
testImplementation 'org.mockito:mockito-core:1.10.19'

编辑:

谢谢大家,在评论中。testImplementation "org.json:json:20190722"确实有效。也许有人可以提供一个答案,如何让它适用于所有这种类型的案例,这样我就不用找半天了……在手机上运行测试?包含特定的android包?那是怎么做的?...或者,至少,做点什么,所以 Android Studio 提供了一个警告,指出某些(看似)标准类没有在测试中实现。

标签: javaandroidjsonunit-testingtostring

解决方案


推荐阅读