Chuyển đến nội dung

Bài 13 · Step Definitions

Custom Parameter Types

Define custom Cucumber parameter types with @ParameterType to turn sentence fragments into enums, dates and domain objects, keeping step definitions free of parsing code.

Built-in types handle numbers and strings. Real sentences are full of other concepts: colors, currencies, plans, dates, user roles. If every step parses these itself, parsing code scatters across the suite and sentences cannot be validated. Custom parameter types solve this: you name a concept once (, , ), say how to recognize it in text and how to convert it to an object, and then every step can use the type like .

The idea in one example

Without a parameter type:

Java
@Given("the user is a {word}")
public void theUserIsA(String role) {
    Role parsed = Role.valueOf(role.toUpperCase());   // fails with an obscure error for "admn"
    ...
}

With a parameter type:

Java
@ParameterType("admin|editor|viewer")
public Role role(String text) {
    return Role.valueOf(text.toUpperCase());
}

@Given("the user is an? {role}")
public void theUserIs(Role role) {
    ...
}

The annotation's string is a regular expression that tells Cucumber what text belongs to the type. The method receives the matched text and returns the object. Three payoffs follow:

  1. Validation in the sentence. the user is a janitor does not match at all, so the step is undefined instead of failing deep inside a conversion.
  2. Single place for parsing. Every step that uses shares the same conversion.
  3. Clean step bodies. The method receives a Role, not a String.

Defining parameter types in Cucumber-JVM

Put the methods in any class on the glue path (conventionally a class named ParameterTypes):

Java
package shop;

import io.cucumber.java.ParameterType;
import java.math.BigDecimal;
import java.time.LocalDate;

public class ParameterTypes {

    @ParameterType("red|green|blue")
    public Color color(String name) {
        return Color.valueOf(name.toUpperCase());
    }

    @ParameterType("\\$(\\d+\\.\\d{2})")
    public BigDecimal money(String amount) {
        return new BigDecimal(amount);
    }

    @ParameterType("\\d{4}-\\d{2}-\\d{2}")
    public LocalDate isoDate(String text) {
        return LocalDate.parse(text);
    }
}

The type name is taken from the method name by default (color, money, isoDate). You can override it with @ParameterType(name = "date", value = "..."). Then steps use it in braces:

Java
@Given("the {color} theme is active")
public void theThemeIsActive(Color color) { ... }

@When("the customer pays {money}")
public void theCustomerPays(BigDecimal amount) { ... }

@Then("the invoice is due on {isoDate}")
public void dueOn(LocalDate date) { ... }

If the regular expression has more than one capture group, the conversion method takes one String parameter per group (use String... groups for flexibility), which is handy for composite values like $12.50 USD.

Other flavors

  • @DefaultParameterTransformer converts any {}/unknown type from a string with a function; it is the fallback for objects.
  • @DataTableType and @DocStringType convert tables and doc strings to objects (covered in chapter 4).
  • useForSnippets and preferForRegexMatch are flags on @ParameterType: the first makes snippets for undefined steps use your type; the second resolves ambiguity when a regex group could match several types.

A parameter-type registry you can run

The stand-in below builds the mechanism. It keeps a registry of named types (a regular expression plus a converter). An expression like the {color} theme costs {money} is compiled by replacing each with the type's regex, and converted arguments are produced by calling the registered converters. Notice what happens with an unregistered color: the sentence is simply undefined.

Java Stand-in: a registry of parameter types

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Compare this with the built-ins: is just another entry, -?\d+ plus Integer::parseInt. Cucumber's own types are defined the same way, which is why custom ones feel native.

Value objects as parameter types

Parameter types are a good place to introduce small domain value objects. A type returning a Money record (amount plus currency) keeps formatting rules in one place; a type might parse "3 months" into a Period. The conversion method can be as rich as you like, but keep it deterministic and free of side effects: it runs while Cucumber matches steps, possibly more than once.

The second stand-in shows a composite type. Its regex has two groups (amount and currency), and the converter receives both and builds a Money record. It also demonstrates the clean step bodies you get: after conversion the step compares two Money values with equals.

Java Stand-in: a Money type with two groups

Press Run (or Ctrl + Enter) to see the result here.

Program input · what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with IO.readln() or a Scanner), it gets the next line from this box.

Naming and design advice

  • Name types after domain concepts (, ), not formats ().
  • Keep the regex tight. If it can match ordinary words, it will compete with other steps and cause ambiguity.
  • Avoid collisions with built-in names such as and .
  • Centralize all parameter types in one or two classes under the glue package so a reader knows where to look.
  • Don't overdo it. One-off values in a single step can stay as ; a type earns its place when two or more steps share it.

You can use the same parameter-type machinery in Kotlin (@ParameterType on a function) and in the other Cucumber implementations, where it is called defineParameterType.

State, not just parameters, must also flow between steps. That is the last lesson of this chapter: sharing state between steps.

Check your understanding

Quick check · 4 questions

of 4 answered You scored / 4 · perfect!

  1. 1. What does the string argument of @ParameterType specify?

    The regex tells Cucumber what text can be matched; the method converts the matched text.
  2. 2. What happens when a sentence contains a value that does not match the type's regex?

    The expression compiled with the custom type simply does not match, which is a clearer error than a late conversion failure.
  3. 3. Where does a custom type take its name by default?

    Use @ParameterType(name = "...") to override it.
  4. 4. Which is good practice for conversion methods?

    They run during matching, so they should be simple pure functions.

Summary

  • A custom parameter type pairs a regex with a conversion, and is used in expressions as .
  • It validates values in the sentence itself and removes parsing from step bodies.
  • Define types in a class on the glue path; the method name is the type name unless overridden.
  • Composite values can use several regex groups; keep converters pure and the regex tight.
  • Built-in types are defined the same way, so custom types behave identically.

Next: Sharing State Between Steps

Theo dõi tiến độ của bạn

Tạo tài khoản miễn phí để đánh dấu bài đã học và tiếp tục từ chỗ bạn dừng lại trên mọi thiết bị.