Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading test data from JSON with TestNG in Java

I'm trying to find the easiest way to parse simple json to java Object for use json data in autotest (TestNG), but I don't understand another examples with various libraries.

I have this code:

@Test(dataProvider = "SearchData") 
public void searchCatTest(String searchRequest, int expectedVal) {
    CatScreen.search(searchrequest);
    int actualVal = CatScreen.getSearchResultsNumber();
    Assert.assertEquals(actualVal, expectedVal);
}

And I have this json:

{   "dataSet": [
    {
      "searchRequest": "*]",
      "expectedVal": 0
    },
    {
      "searchRequest": "Tom",
      "expectedVal": 1
    },
    {
      "searchRequest": "1234",
      "expectedVal": 0
    }   ] }

How can I linked them?

like image 643
Dmitrij Avatar asked Mar 09 '26 06:03

Dmitrij


1 Answers

@DataProvider(name = "json-data")
public static Object[][] getJSON(ITestContext context) throws FileNotFoundException {
    String filename = <get name from context>
    JsonArray array = new JsonParser().parse(new FileReader(filename))
       .getAsJsonArray();
    Gson gson = new Gson();
    List < Map > list = gson.fromJson(array, List.class);
    Object[][] objects = list.stream()
        .map(testData - >
            testData.values().stream().map(obj - > 
              doubletoint(obj)).toArray()).toArray(Object[][]::new);
    return objects;
}

TestNG will create a new thread per row of data.

like image 96
Dmitrij Avatar answered Mar 10 '26 19:03

Dmitrij



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!