How to Iterate Datatable with type List<Class> in Cucumber

China☆狼群 提交于 2019-12-24 18:19:30

问题


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:


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



来源:https://stackoverflow.com/questions/49117502/how-to-iterate-datatable-with-type-listclass-in-cucumber

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!