Dmitrij
Dmitrij

Reputation: 51

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?

Upvotes: 3

Views: 5601

Answers (2)

Dmitrij
Dmitrij

Reputation: 51

@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.

Upvotes: 2

Suraj Jogdand
Suraj Jogdand

Reputation: 306

You can use the following library to parse the json code to java :

        <dependency>
            <groupId>com.googlecode.json-simple</groupId>
            <artifactId>json-simple</artifactId>
            <version>1.1.1</version>
        </dependency>

You can refer the this link for how to parse the json code.

Upvotes: 0

Related Questions