NarendraR
NarendraR

Reputation: 7708

Store List<DataBean> into two dimention Object[][]

I'm trying to deserialize an array of json object to array of java Object. I'm using data provider to pass this data combination to test methods so test method executes for each data set.

I've created Data provider method as mentioned below and deserilised the Json:

@DataProvider(name = "listData")
public Object[][] listData() throws FileNotFoundException {
    Type listType = new TypeToken<List<DataBean>>() {
    }.getType();
    List<DataBean> data = new GsonBuilder().create().fromJson(new FileReader("resources/data.json"), listType);
    data.forEach(iterator -> System.out.println(iterator.getUsername() + " : : " + iterator.getPassword()));
    return new Object[][]{data.toArray()};
}

Test method :

@Test(dataProvider = "jsonData")
public void testdata(DataBean dataBean) {
    System.out.println(dataBean.getUsername() + "============" + dataBean.getPassword());

}

and JSON :

[
  {
    "username": "someuser",
    "password": "abc#add"
  },
  {
    "username": "anotheruser",
    "password": "daa#add"
  }
]

Unfortunately its not working. If i use Strong typed Object like below then its work as expected :

    return new Object[][]{{new DataBean("user1", "d121312")},
            {new DataBean("user2", "asdsd")}};

Error:

org.testng.internal.reflect.MethodMatcherException: [public void com.mind.DataProviderUtil.testdata(com.mind.DataBean)] has no parameters defined but was found to be using a data provider (either explicitly specified or inherited from class level annotation). Data provider mismatch Method: testdata([Parameter{index=0, type=com.mind.DataBean, declaredAnnotations=[]}]) Arguments: [(com.mind.DataBean) com.mind.DataBean@78b66d36,(com.mind.DataBean) com.mind.DataBean@5223e5ee]

Can someone please help me int storing List<DataBean> data in Object[][] so my test method execute for each set of data

Upvotes: 0

Views: 93

Answers (1)

NarendraR
NarendraR

Reputation: 7708

Data stores in 2-D array in matrix form.

Lets say there is an array of 3x3 then matrix representation would be

1     2     1   

3     4     2

1     2     1

As data provider return 2-D array to supply data to Test method for Data Driven test. So need to mention Object[][] with proper size. I've 2 sets of data in JSON file and I'm deserializing to a JAVA object that is DataBean in my case. So here I have to mention sizes as Object[dataBean.size()][1]

Complete Code:

    Type listType = new TypeToken<List<DataBean>>() {
    }.getType();
    List<DataBean> bean = new GsonBuilder().create().fromJson(new FileReader("resources/data.json"), listType);
    bean.forEach(iterator -> System.out.println(iterator.getUsername() + " : : " + iterator.getPassword()));
    Object[][] data = new Object[bean.size()][1];
    for (int i = 0; i < bean.size(); i++) {
        data[i][0] = bean.get(i);
    }
    return data;

Upvotes: 0

Related Questions