原标题:What does scalar in Cucumber DataTables in Java?
来自 this引用:
Java provides several scalar types. These include primitive numeric types, plus boolean and char.
Every scalar (primitive) type has an associated wrapper class or reference type.
阅读javadocs:
/**
* Converts the table to a List.
*
* If {@code itemType} is a scalar type the table is flattened.
*
* Otherwise, the top row is used to name the fields/properties and the remaining
* rows are turned into list items.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a List of objects
*/
public <T> List<T> asList(Class<T> itemType) {
return tableConverter.toList(this, itemType);
}
/**
* Converts the table to a List of List of scalar.
*
* @param itemType the type of the list items
* @param <T> the type of the list items
* @return a List of List of objects
*/
public <T> List<List<T>>> asLists(Class<T> itemType) {
return tableConverter.toLists(this, itemType);
}
但是,我能够在 asList() 中传递 String.class:
List<String> list = dataTable.asList(String.class);
字符串在 Java 中不是原语。我想澄清一下“标量”在这种情况下的含义。
最佳答案
引用生成的代码片段:
// For automatic transformation, change DataTable to one of
// List<YourType>, List<List<E>>, List<Map<K,V>> or Map<K,V>.
// E,K,V must be a scalar (String, Integer, Date, enum etc)
Cucumber javadoc 中的“标量”可能被错误地统称为原语(即标量)的关联包装类。
在下面的示例中,asList()
按照文档继续创建用户定义的费用对象列表:
Otherwise, the top row is used to name the fields/properties and the remaining rows are turned into list items.
我观察到以下情况:
- 特征文件中的顶行(标题)必须匹配字段 对象的名称。
- 构造函数可以接受所有字段作为参数。
用户定义对象(非标量):
public class Expense {
private String name = null;
private String amount = null;
private String frequency = null;
public Expense(String name, String amount, String frequency) {
this.name = name;
this.amount = amount;
this.frequency = frequency;
}
// Getters and setters
}
特征:
When I Enter My Regular Expenses
| name | amount | frequency |
| Electricity | 5500 | Monthly |
| Water | 900 | Weekly |
| Internet | 1900 | Every 2 Weeks |
| Cable TV | 555 | Daily |
步骤定义:
@When("^I Enter My Regular Expenses$")
public void I_Enter_My_Regular_Expenses(DataTable dataTable) throws Throwable {
List<Expense> expenseList = dataTable.asList(Expense.class);
for (Expense expense : expenseList) {
System.out.println(expense);
}
// Here, asList() creates a List of Expense objects.
}
输出:
关于java - 如何将 Cucumber 中的 DataTable 转换为对象列表?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46130455/