您可以实现一个新的参数转换器,然后将表作为对象传递。例如,在我们的项目中,我们构建了 ExamplesTableConverter(注意:有一个我们没有测试的盒子 JBehave 转换器):
public class ExamplesTableConverter extends ParameterConverters.ExamplesTableConverter {
private final ExamplesTableFactory factory;
private static final String ROW_SEPARATOR = "\n";
private static final String FIELD_SEPARATOR = "|";
public ExamplesTableConverter(){
this(new ExamplesTableFactory());
}
public ExamplesTableConverter(ExamplesTableFactory factory){
this.factory = factory;
}
@Override
public boolean accept(Type type) {
if (type instanceof Class<?>){
return ExamplesTable.class.isAssignableFrom((Class<?>) type);
}
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public Object convertValue(String tableAsString, Type type) {
System.out.println(tableAsString);
String[] rows = tableAsString.split(ROW_SEPARATOR);
StringBuffer resultString = new StringBuffer();
resultString.append(rows[0]);
resultString.append(ROW_SEPARATOR);
for(int i=1; i<rows.length; i++){
String originRow = rows[i];
List<String> rowValues = TableUtils.parseRow(originRow, FIELD_SEPARATOR, true);
String translatedRow = translateRow(rowValues);
resultString.append(translatedRow);
resultString.append(ROW_SEPARATOR);
}
System.out.println(resultString.toString());
Object table = factory.createExamplesTable(resultString.toString());
return table;
//return null;
}
private String translateRow(List<String> rowValues) {
StringBuffer result = new StringBuffer(FIELD_SEPARATOR);
for(String field : rowValues){
try{
result.append(translate(field));
result.append(FIELD_SEPARATOR);}
catch (LocalizationException e){
e.printStackTrace();
//Need do something here to handle exception
}
}
return result.toString();
}
}
那么您需要将该转换器添加到您的配置中:
configuration.parameterConverters().addConverters(new ExamplesTableConverter());
创建一个使用它的方法
@When("create parameters of type $param1 from the next table: $table")
public void doThis(@Named("param1") String param1, @Named("table") ExamplesTable table)
最后,在故事中使用它:
When create parameters of type type1 from the next table:
|FirstName|LastName|
|Donald|Duck|
这将允许您迭代表。
以下博客文章也可以帮助您
更简单的 JBehave 示例表处理