如何编写junit测试用例解析jsonresponse?

问题描述

我正在尝试编写一个测试用例,其中条件是我必须读取一个 json 文件,然后如果 valuesdata 为真,则它必须具有 values 属性,当它为假时,则应具有 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);
            }
        }
    }