Search code examples
javacucumbergherkin

Date object in Cucumber


I have a cucumber stepdef like this

Given the date of <date>
When blah blah
Then x y and z
Examples:
|2015-01-01|
|2045-01-01|

When I generate stepdefs off of this, I get @Given("^the date of (\\d+)-(\\d+)-(\\d+)$") And the method is generated with three integers as parameters. How can I tell Cucumber to treat it like a Java.Time LocalDate? Is there a way to create a mapper that Cucumber will understand? Or at the very least, is there a way to treat that date object as a string instead of three numbers?


Solution

  • With Cucumber 7, I'm defining a new @ParameterType :

    @ParameterType("\\d{2}\\.\\d{2}\\.\\d{4}")
    public LocalDate mydate(String dateString) {
        return LocalDate.parse(dateString, DateTimeFormatter.ofPattern("dd.MM.yyyy"));
    }
    

    Then I can use step definition @Given such as :

    @Given("person has birthdate {mydate}")
    public void person_birthdate(LocalDate birthDate) {
        ... // do something
    }
    

    The placeholder name {mydate} is the name of the mapping method, but you can override it through @ParameterType.name.