java - 如何编写junit测试用例解析jsonresponse?
问题描述
我正在尝试编写一个测试用例,其中条件是我必须读取一个 json 文件,然后如果 valuesdata 为 true,则它必须具有 values 属性,当它为 false 时,它应该具有 sql 属性
{
"data": [
{
"valuesdata": true,
"values": [
{
"id": "1"
}
]
},
{
"valuesdata": false,
"sql": "select * from data"
}
]
}
这是我试图写的,任何帮助表示赞赏
import org.json.JSONObject;
import org.junit.Assert;
import org.junit.jupiter.api.DisplayName;
import org.junit.jupiter.api.Test;
public class Test{
@Test
@DisplayName("If Json valuesdata is true it should have values attribute")
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
jsonObjects.getJSONArray("data").getJSONObject(0).getBoolean("valuesdata");
}
}
解决方案
您可以考虑:
@Test
public void dropdownJsonValueIsStaticTrue() throws Exception {
String content = new String(Files.readAllBytes(Paths.get(input_file_path)));
JSONObject jsonObjects = new JSONObject(content);
JSONArray datas = jsonObjects.getJSONArray("data");
for (int i = 0 ; i < datas.length(); i++) {
JSONObject data = datas.getJSONObject(i);
boolean valuesdata = data.getBoolean("valuesdata");
if(valuesdata) {
assertTrue(data.getJSONArray("values") != null);
} else {
assertTrue(data.getString("sql") != null);
}
}
}
推荐阅读
- reactjs - @import - 将 scss 文件放入另一个 scss 文件时出现意外标记
- python - 结合每两行的熊猫操作
- javascript - Tealium Javascript 代码扩展如何返回一个变量
- javascript - 如何使用 ReplaceWith 并将结果放入输入
- mongodb - 项目索引数组mongodb
- java - 删除所有出现的字符“。” 来自Java中的字符串
- node.js - Nest.js 中的优雅环境处理
- git - github 中的代码审查和拉取请求工作流程
- android - React Native Android 剪辑儿童
- angular - 如何从孙子路由到子孙