问题
I have the following datatable in a Gherkin file:
Given the system knows about the following equipments:
| SerialNumber | CreationDate |
| 1234A | 2016-05-17T08:41:17.970Z |
| 5678A | 2012-03-16T08:21:17.970Z |
And the following matching step definition in java :
@Given("^the system knows about the following equipments:$")
public void theSystemKnowsAboutTheFollowingEquipments(List<Equipment> equipments) throws Throwable {
// step code...
}
With the POJO Equipment.java :
public class Equipment {
private String equipmentId;
private LocalDateTime creationDate;
}
Since cucumber does not support LocalDateTime transformation by default, I would like to register my custom xstream Transformer in order for LocalDateTime to be handled correctly inside my Equipment POJO. Is there a way to do this?
回答1:
Assuming that you have access to the code of the Equipment POJO.
You can use the @XStreamConverter annotation to register your XStream converter class.
The column names in the datatable and fields in the desired POJO need to match so that Cucumber can do its magic of matching columns to respective fields.
Create a custom
DTZConverterclass extendingAbstractSingleValueConverterfor the DateTime parsing logic. Do modify the pattern used below.
public class DTZConverter extends AbstractSingleValueConverter { @Override public boolean canConvert(Class type) { return type.equals(LocalDateTime.class); } @Override public Object fromString(String dtz) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm"); return LocalDateTime.parse(dtz, formatter); } }
- Annotate the creationDate field with
@XStreamConverter(DTZConverter.class).
public class Equipment { private String equipmentId; @XStreamConverter(DTZConverter.class) private LocalDateTime creationDate; @Override public String toString() { return "Equipment [equipmentId=" + equipmentId + ", creationDate=" + creationDate + "]"; } }
回答2:
How about registering your object in the type registry and letting jackson convert it for you:
Create a class implementing cucumber.api.TypeRegistryConfigurer
Implement method configureTypeRegistry as below:
private static ObjectMapper objectMapper = new com.fasterxml.jackson.databind.ObjectMapper();
.....
.....
@Override
public void configureTypeRegistry(TypeRegistry typeRegistry) {
typeRegistry.defineDataTableType(new DataTableType(
Equipment.class,
(Map<String, String> row) -> objectMapper.convertValue(row, classType))
);
}
And that's it!
来源:https://stackoverflow.com/questions/42027000/register-localdatetime-xstream-transformer-with-cucumber-datatable