首页 > 解决方案 > 如何编写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");
            
        }
}

标签: javajunitjunit4junit5

解决方案


您可以考虑:

    @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);
            }
        }
    }

推荐阅读