Search code examples
javajunitjunit4junit5

How to write junit test case parsing jsonresponse?


I am trying to write a test case in which the condition is I have to read a json file then if valuesdata is true then it must have values attribute and when it is false then it should have sql attribute

{
  "data": [
    {
      "valuesdata": true,
      "values": [
        {
          "id": "1"
        }
      ]
    },
    {
      "valuesdata": false,
      "sql": "select * from data"
    }
  ]
}

This is what I was trying to write , any help is appreciated

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

Solution

  • You can consider that :

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