Exit course
Chapter 5 of 12 Intermediate 8 min read 3 quick checks Updated

Step Definitions, Cucumber Expressions, Parameter Types

On this page
  1. How Cucumber finds a step definition
  2. Snippets for undefined steps
  3. Cucumber expressions
  4. Custom parameter types
  5. Data tables
  6. Keep step definitions thin

Chapter 3's steps matched their text literally, which only works for one scenario. Real suites need steps that take values (a name, an amount, a field), steps that read naturally in more than one form, and a way to turn the words in a scenario into domain objects. That is what Cucumber expressions and parameter types are for.

To keep the examples short, the method bodies in this chapter call a small SignInPage class instead of Selenium directly. Chapter 5 shows that class and how it gets into the step definitions.

How Cucumber finds a step definition#

When Cucumber runs a step, it takes the text after the keyword (Given, When...) and compares it against every step definition in the glue path. The keyword does not matter for matching: @Given("Tom has an account") also matches When Tom has an account or And Tom has an account.

There are three possible outcomes:

  • Exactly one match: the method runs, with any captured values as arguments.
  • No match: the step is undefined. The scenario fails, the remaining steps are skipped, and Cucumber prints a snippet you can paste.
  • More than one match: the step is ambiguous and the scenario fails. Cucumber never guesses.

Because every step definition is visible to every feature file, step definitions are a shared vocabulary for the whole project, not a private helper for one feature. Grouping them by domain concept (SignInSteps, BasketSteps) rather than by feature file keeps that vocabulary findable.

Snippets for undefined steps#

Write the scenario first and let Cucumber tell you what to implement. With this step in a feature file and no matching code:

When Tom resets his password to "n3w-Pass"
Then he receives 1 email

the run fails with a snippet for each missing step:

@When("Tom resets his password to {string}")
public void tom_resets_his_password_to(String string) {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java.PendingException();
}
@Then("he receives {int} email")
public void he_receives_email(Integer int1) {
    // Write code here that turns the phrase above into concrete actions
    throw new io.cucumber.java.PendingException();
}

Cucumber guessed that "n3w-Pass" is a string and 1 is a number. Rename the method and the parameters before you commit them; string and int1 will not help the next reader.

Cucumber expressions#

The text in the annotation is a Cucumber expression. It looks like the step, with placeholders in braces:

Placeholder Matches Java type
{int} 42, -7 Integer / int
{float} 3.5 Float / float ({double}, {long}, {bigdecimal} also exist)
{word} one word without spaces, tomsmith String
{string} text in double or single quotes, "Buy milk" String (without the quotes)
{} anything String, or converted to the parameter's type

Two more pieces of syntax make steps read naturally:

  • Optional text in parentheses: he receives {int} email(s) matches both "1 email" and "2 emails".
  • Alternative text with a slash: {member} signs in with his/her password matches "his" and "her". Alternatives are single words; there is no space around the slash.
@When("someone signs in as {string} with password {string}")
public void someoneSignsIn(String username, String password) {
    signInPage.signIn(username, password);
}

If an expression is not enough you can still write a regular expression: Cucumber treats an annotation that starts with ^ or ends with $ as a regex. In practice a Cucumber expression with a custom parameter type is almost always clearer.

A project has @Given("Tom has an account") and a feature file contains When Tom has an account. What happens?

Cucumber matches only the text after the keyword. That is why a Given that sometimes appears as a When still works, and also why the choice of keyword is purely for the reader.

Custom parameter types#

Scenarios talk in domain terms: "Tom", "the password", "a gold customer". A parameter type turns such a word into an object before your step definition sees it, so the conversion lives in one place.

The sign-in feature has two: members, and the field that was wrong.

package com.example.support;

public record Member(String name, String username, String password) {}
package com.example.support;

public enum Field { USERNAME, PASSWORD }
package com.example.support;

import io.cucumber.java.ParameterType;

public class ParameterTypes {

    @ParameterType("Tom")
    public Member member(String name) {
        return switch (name) {
            case "Tom" -> new Member("Tom", "tomsmith", "SuperSecretPassword!");
            default -> throw new IllegalArgumentException("Unknown member " + name);
        };
    }

    @ParameterType("username|password")
    public Field field(String name) {
        return Field.valueOf(name.toUpperCase());
    }
}
  • The name of the parameter type is the method name: member becomes {member}, field becomes {field}.
  • The regular expression in the annotation says which words match. "Tom" only matches Tom; add personas as you need them ("Tom|Ana").
  • The method converts the matched text. Anything it throws fails the step with a clear message.

The class must be in the glue path, like step definitions. Now steps can take domain objects:

@Given("{member} has an account")
public void hasAnAccount(Member member) {
    this.member = member;
}

@When("{member} signs in with his/her password")
public void signsInWithPassword(Member member) {
    signInPage.signIn(member.username(), member.password());
}

@Then("the sign-in is rejected because the {field} is invalid")
public void rejectedBecause(Field field) {
    String expected = switch (field) {
        case USERNAME -> "Your username is invalid!";
        case PASSWORD -> "Your password is invalid!";
    };
    assertTrue(signInPage.flashMessage().contains(expected),
            () -> "Expected \"" + expected + "\" in \"" + signInPage.flashMessage() + "\"");
    assertEquals("Login Page", signInPage.heading());
}

The test data for Tom lives in one method. When the demo password changes, nothing in the feature files does. And a typo such as the sign-in is rejected because the pasword is invalid is not silently accepted: {field} only matches username or password, so the step is undefined and the run fails.

Ten step definitions each look up a customer by name with their own switch. What does a {customer} parameter type change?

A parameter type centralises the conversion from words to domain objects. Steps get typed arguments, and an unknown customer fails in one obvious place instead of ten.

Data tables#

When a step needs several related values, a data table under the step reads better than a long sentence:

Scenario: Tom mistypes his password
  When someone signs in with:
    | username | tomsmith |
    | password | wrong    |
  Then the sign-in is rejected because the password is invalid

Declare a parameter of a collection type and Cucumber converts the table. A two-column table becomes a Map:

@When("someone signs in with:")
public void someoneSignsInWith(Map<String, String> credentials) {
    signInPage.signIn(credentials.get("username"), credentials.get("password"));
}

Tables with a header row convert to List<Map<String, String>> (one map per row), and with a @DataTableType method you can turn each row into your own record. Use tables for data the reader needs to see; if nobody needs to see it, it belongs in a parameter type or in the step definition. And notice that the step above is more imperative than "Tom mistypes his password": tables make it easy to slide back into test scripts.

Keep step definitions thin#

A step definition should translate, not implement. It reads the arguments, calls something that knows how to drive the system (a page object, an API client, a domain service), and asserts the outcome. When Selenium calls start piling up in step definitions, the same locators get copied into several classes and every UI change hurts. The Page Object Model course covers the pattern in depth; chapter 5 applies the minimal version to this project.

Two classes define @When("{member} signs in") and @When("Tom signs in"). A scenario says When Tom signs in. What happens?

Cucumber does not rank matches. Two definitions matching the same text is an error, which forces you to keep one vocabulary. Delete the duplicate.