Tuesday, August 24, 2021

Merging more than one data providers in TestNG

 We can merge more than one data providers into.

EX:

public Object[][] dp1() {
return new Object[][] {{ "a", "b" },{ "c", "d" }};
}
public Object[][] dp2() {
return new Object[][] {{ "e", "f" },{ "g", "h" }};
}

@DataProvider
public Object[][] dp() {
List<Object[]> result = Lists.newArrayList();
result.addAll(Arrays.asList(dp1()));
result.addAll(Arrays.asList(dp2()));
return result.toArray(new Object[result.size()][]);
}

@Test(dataProvider = "dp")
public void f(String a, String b) {
System.out.println("f " + a + " " + b);
}

 

Sunday, August 1, 2021

Json dataset to DataProvider

 public class JsonReader {

    public static Object[][] getData(String jsonPath, String dataObject, int totalDataRow, int totalColumnEntry)
            throws Exception {

        JsonParser jsonParser = new JsonParser();
        JsonObject jsonObj = jsonParser.parse(new FileReader(jsonPath)).getAsJsonObject();
        JsonArray array = (JsonArray) jsonObj.get(dataObject);
        return searchJsonElement(array, totalDataRow, totalColumnEntry);

    }

    public static Object[][] toArray(List<List<Object>> list) {
        Object[][] r = new Object[list.size() + 1][];
        int i = 0;
        for (List<Object> next : list) {
            r[i++] = next.toArray(new Object[list.size() + 1]);
        }
        return r;
    }

    public static Object[][] searchJsonElement(JsonArray jsonArray, int totalDataRow, int totalColumnEntry)
            throws Exception {
        Object[][] matrix = new Object[totalDataRow][totalColumnEntry];
        int i = 0;
        int j = 0;
        for (JsonElement jsonElement : jsonArray) {
            for (Map.Entry<String, JsonElement> entry : jsonElement.getAsJsonObject().entrySet()) {
                matrix[i][j] = entry.getValue().toString().replace("\"", "");
                j++;
            }
            i++;
            j = 0;
        }
        return matrix;
    }


    public static void main(String[] args) throws Exception {

        String Json_path = "D:\\xxx\\xxx\\Login.json";
        Object[][] data = JsonReader.getData(Json_path, "LoginData", 2, 3);
        System.out.println(Arrays.deepToString(data));
    }
}