Это сработало, но не совсем точно как.Если кто-то может добавить однострочные комментарии или оставить объяснение, было бы здорово для справки для всех.Спасибо!
Тип
public class Transaction {
private String name = null;
private String amount = null;
private String frequency = null;
private String month = null;
public Transaction() {
// Empty constructor
}
public Transaction(Map<String, String> entry) {
this.name = entry.get("name");
this.amount = entry.get("amount");
this.frequency = entry.get("frequency");
this.month = entry.get("month");
}
// getters and setters
}
Функция
And I Enter My Regular Income Sources
| name | Salary |
| amount | 25000 |
| frequency | every 2 weeks |
And I Enter My Regular Expenses
| name | amount | frequency |
| Electricity | 5500 | Monthly |
| Water | 900 | Weekly |
| Internet | 1900 | Every 2 Weeks |
| Cable TV | 555 | Daily |
StepDef
@When("I Enter My Regular Income Sources")
public void I_Enter_My_Regular_Income_Sources(@Transpose Transaction transaction) throws Throwable {
// vertical datatable transforms to a single object
// column 1 = field name, column 2 = value
}
@When("I Enter My Regular Expenses")
public void I_Enter_My_Regular_Expenses(DataTable table) throws Throwable {
// datatable with header row transforms to a List of objects
// 1 row = 1 object
List<Transaction> transactions = table.asList(Transaction.class);
}
Конфигуратор
public class Configurer implements TypeRegistryConfigurer {
@Override
public Locale locale() {
return Locale.ENGLISH;
}
@Override
public void configureTypeRegistry(TypeRegistry registry) {
JacksonTableTransformer jtt = new JacksonTableTransformer();
registry.setDefaultParameterTransformer(jtt);
registry.setDefaultDataTableCellTransformer(jtt);
registry.setDefaultDataTableEntryTransformer(jtt);
/*
* Maps DataTable with label column to a single object of Type<T>. Left column
* is field name, right column is value.
*/
registry.defineDataTableType(new DataTableType(Transaction.class, new TableTransformer<Transaction>() {
@Override
public Transaction transform(DataTable table) throws Throwable {
return new Transaction(table.asMaps().get(0));
}
}));
}
private static final class JacksonTableTransformer
implements ParameterByTypeTransformer, TableCellByTypeTransformer, TableEntryByTypeTransformer {
private final ObjectMapper objMapper = new ObjectMapper();
@Override
public Object transform(String fromValue, Type toValueType) throws Throwable {
return objMapper.convertValue(fromValue, objMapper.constructType(toValueType));
}
@Override
public <T> T transform(String value, Class<T> cellType) throws Throwable {
return objMapper.convertValue(value, cellType);
}
@Override
public <T> T transform(Map<String, String> entry, Class<T> type, TableCellByTypeTransformer cellTransformer)
throws Throwable {
return objMapper.convertValue(entry, type);
}
}
}