How to Iterate Datatable with type List in

2019-08-17 17:26发布

I have below feature file with Given annotation

Given user have below credentials
|user       |password |
|cucumber1  |cucumber |
|cucumber2  |cucumber |

And i'm created below datamodel

public Class DataModel{
   public string user;
   public String password;
}

Trying to fetch data into the cucumber stepdefinition as below

Public Class stepdefinition {
 @Given("^user have below credentials$")
   Public void user_have_below_credintials(List<DataModel> dm){

       //Iterator or foreach is required to fetch row,column data from dm
   }
}

Please help me how can I Iterate object 'dm' to get row and column values

1条回答
Deceive 欺骗
2楼-- · 2019-08-17 17:33
// The old way
for (int i = 0; i < dm.size(); i++) {
    DataModel aDataModel = dm.get(i);
    String username = aDataModel.user;
    String password = aDataModel.password;
}

// A better way if java5+
for (DataModel aDataModel : dm) {
    String username = aDataModel.user;
    String password = aDataModel.password;
}

// another way if java8+
dm.forEach(aDataModel -> {
    String username = aDataModel.user;
    String password = aDataModel.password;
});

Note that the variables won't be available outside the loop with the way I wrote it. Just a demonstration of iterating and accessing the properties of each DataModel in your list.

A thing to keep in mind is that you're describing your list of DataModel objects as a data table. But it's not a table, it's simply a collection of values contained in an object, which you have a list of. You may be displaying it, or choosing to conceptualize it as a data table in your head, but the model that your code is describing isn't that, which means you aren't going to iterate through it quite like a table. Once you access a "row", the "columns" have no defined order, you may access them in any order you want to the same effect.

查看更多
登录 后发表回答