java - 在单元测试中使用 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 提供了一个警告,指出某些(看似)标准类没有在测试中实现。
解决方案
推荐阅读
- vba - 尝试使用 excel VBA 访问网站上的数据,我需要能够单击按钮
- python-2.7 - Paramiko 在遇到缺少输出时挂起
- sql - 当到期日总是在每个月的最后一天时,查找不同的 ID
- c# - 如何在服务器端防止href属性的xss?
- android - Android 上的 Tensorflow 推理,找不到“迭代器”操作。没有注册 OpKernel 来支持 Op
- html - 在jsx onclick按钮中使用href
- php - PHP OCI BIND-IN & BIND-OUT 问题
- python - scapy 信标包的信号强度,负整数到二进制补码十六进制
- c++ - 对象赋值 - 无效使用成员函数错误
- javascript - HTML事件同时弹出,怎么选一个