Answer
@ParameterType — Custom Cucumber Expressions
Problem Without Custom Types
Java
// Step text: When the user selects "ADMIN" role
@When("the user selects {string} role")
public void selectRole(String roleString) {
Role role = Role.valueOf(roleString); // manual conversion everywhere
userPage.selectRole(role);
}
Solution: @ParameterType
Java
import io.cucumber.java.ParameterType;
public class CustomTypes {
// Define custom type {role} that maps string → enum
@ParameterType("ADMIN|MANAGER|USER|GUEST")
public Role role(String roleString) {
return Role.valueOf(roleString);
}
// Custom type for date
@ParameterType("\\d{4}-\\d{2}-\\d{2}")
public LocalDate date(String dateString) {
return LocalDate.parse(dateString);
}
// Custom type for money
@ParameterType("\\$\\d+\\.?\\d*")
public BigDecimal amount(String amountString) {
return new BigDecimal(amountString.replace("$", ""));
}
}
Using Custom Types in Feature Files
Gherkin
Scenario: Admin creates new user
When the admin assigns the ADMIN role to the new user
Then the user should have ADMIN permissions
Scenario: Filter transactions by date
When the user filters transactions from 2024-01-01 to 2024-12-31
Then all transactions in that period should appear
Scenario: Apply discount
When the user applies a discount of $15.00
Then the cart total should reduce by $15.00
Step Definitions Using Custom Types
Java
// Now uses {role} instead of {string}
@When("the admin assigns the {role} role to the new user")
public void assignRole(Role role) {
// role is already a Role enum — no conversion needed
adminPage.assignRole(role);
}
@When("the user filters transactions from {date} to {date}")
public void filterByDate(LocalDate from, LocalDate to) {
// Already LocalDate objects — no parsing needed
reportPage.setDateRange(from, to);
}
@When("the user applies a discount of {amount}")
public void applyDiscount(BigDecimal amount) {
cartPage.applyDiscount(amount);
}
Built-in Cucumber Expressions
Java
{string} → "quoted text" → String
{int} → 42 → Integer
{float} → 3.14 → Float / Double
{word} → singleword → String
{bigdecimal}→ 9.99 → BigDecimal
{long} → 123456789 → Long
{} → anything → String (anonymous)
Cucumber Expression vs Regex
Java
// Cucumber Expression (simpler, recommended)
@When("the user enters {string} into the {word} field")
// Regex (more powerful, harder to read)
@When("^the user enters \"([^\"]*)\" into the (\\w+) field$")
Use Cucumber Expressions for most cases. Use Regex only when you need complex pattern matching that {} types can''t express.
