Retrieving JSON data outside of test methods

It is often required to create a common setup or teardown method that also uses data from a JSON file. In those cases, you would not pass in a DataProvider attribute to the method, but instead call an extraction method directly.

The following code samples are a variation of the DataProvider's fetchData method. These methods allow the user to extract the set(s) of data using rowID and return it as a JSONObject or JSONArray object. These objects can then be cast to a POJO that the user defines:

// extractData_JSON method - create JSONObject containing all data sets
public static JSONObject extractData_JSON(String file) throws Exception {
FileReader reader = new FileReader(file);
JSONParser jsonParser = new JSONParser();

return (JSONObject) jsonParser.parse(reader);
}

In the preceding example, the method extracted all sets of data from the file and returned them as a JSONObject. But users would most likely want just specific sets of data to use, so the next example shows how to add a filter to pull just specific sets of data. The method returns them as a JSONArray of objects, one for each set of data:

// fetchDataSet method - create JSONArray containing specific data sets
public static
JSONArray fetchDataSet(String file,
String rowID)
throws Exception {

JSONArray testData = (JSONArray) extractData_JSON(file).get(rowID);

return testData;
}

Finally, in the following setup method, the data is fetched from within the method and parsed, printing out the values for each object:

// getBandInfo method - extract and print each band info data set
public void getBandInfo(String file,
String rowID)
throws Exception {

JSONArray testData = fetchDataSet(file, rowID);

for ( int i = 0; i < testData.size(); i++ ) {
RockBands rockBands = new RockBands((JSONObject)
testData.get(i));
System.out.println(rockBands.toString() + " ");
}
}
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
18.221.187.121