Skip to content
Tutorials Center
My learning

Topics

Lesson 10 of 37 ยท Step Definitions

Step Definition Basics

Write Cucumber-JVM step definitions: the Given, When and Then annotations, method signatures, assertions, pending steps, ambiguity errors, class organization and Kotlin.

A step definition is a method with an annotation. The annotation holds an expression that matches sentences, and the method body does something to the system. Everything else in Cucumber (hooks, tags, parameter types) exists to make that connection convenient. This lesson covers the shape of a step definition, how Cucumber discovers it, the rules for ambiguity, and how to organize step classes as a project grows.

Anatomy of a step definition

Java
package shop;

import io.cucumber.java.en.Given;
import io.cucumber.java.en.When;
import io.cucumber.java.en.Then;

import static org.junit.jupiter.api.Assertions.assertEquals;

public class CartSteps {

    private int bookPrice;
    private int booksInCart;

    @Given("a book costing {int} dollars")
    public void aBookCostingDollars(int price) {
        bookPrice = price;
    }

    @When("the customer adds {int} book(s)")
    public void theCustomerAddsBooks(int count) {
        booksInCart += count;
    }

    @Then("the cart total is {int} dollars")
    public void theCartTotalIsDollars(int expected) {
        assertEquals(expected, bookPrice * booksInCart);
    }
}

The ingredients:

  • Annotation: @Given, @When, @Then (and @And, @But, which are rarely used because keywords do not matter for matching). They come from io.cucumber.java.en; other language packages exist (io.cucumber.java.fr, .de and so on) and match localized keywords.
  • Expression: the string argument. and book(s) are Cucumber expression syntax, the subject of the next lesson.
  • Method: any public method. Its name does not matter to Cucumber; choose a name that explains it to a human.
  • Parameters: one per placeholder, in order, converted to the declared Java type.
  • Return type: void. A non-void return value is ignored.

Keywords do not matter

A sentence Given a book costing 12 dollars is matched by looking only at a book costing 12 dollars. The keyword does not take part. The consequence: a definition declared with @Given also matches the same text after a When. Use that freedom sparingly, since readers expect the keyword roles to hold, but it means you can write And a book costing 5 dollars after a When without trouble.

Assertions

Cucumber has no assertion library of its own. A step fails when it throws any exception; AssertionErrors thrown by JUnit, AssertJ or Hamcrest are the norm. Choose one library and use it everywhere. AssertJ reads nicely:

Java
import static org.assertj.core.api.Assertions.assertThat;

@Then("the cart contains {int} books")
public void theCartContainsBooks(int expected) {
    assertThat(cart.size()).isEqualTo(expected);
}

Place assertions only in @Then methods, as discussed in the first feature lesson.

Pending, skipped and undefined

Throwing io.cucumber.java.PendingException marks the step as pending: "I know this step, but it is not implemented". Cucumber treats pending steps as failures in strict mode, which is the default. Use it in the first draft of a step and remove it as soon as the body is real. org.junit.jupiter.api.Assumptions.assumeTrue(false) produces a skipped result instead, which some teams use for scenarios that only apply to certain environments.

Discovery: how Cucumber finds your steps

Cucumber scans the glue package (set in the runner), loads each class, and collects annotated methods. This is reflection: the same trick as the stand-in below. The stand-in defines three annotations, a step class with annotated methods, scans the class for annotations, and uses them to run a scenario. It is a faithful miniature of what Cucumber-JVM does when it starts up.

Java Stand-in: step definitions discovered by annotation

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.

The real implementation adds expression parsing, type conversion, caching, dependency injection and parallelism, but the skeleton is this: find annotated methods, compile their expressions, match, convert, invoke, and turn an exception into a failed step.

Ambiguous and duplicate definitions

Two failure modes arise from the matching process:

  • Duplicate step definition: two methods with the same expression text. Cucumber detects this at start-up and aborts. The fix is to delete one.
  • Ambiguous step: two different expressions that both match one sentence, for example the cart total is {int} dollars and the cart total is {int} {word}. Cucumber reports the sentence and both definitions and fails the step. The fix is to tighten one expression so they no longer overlap.

The stand-in below lists, for each sentence, how many definitions match, flagging 0 as undefined and 2 or more as ambiguous. Run it, then fix the ambiguity by editing the second pattern.

Java Stand-in: undefined and ambiguous steps

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.

Organizing step classes

As a suite grows, CartSteps turns into a thousand-line class. Split by domain concept, not by keyword:

TEXT
steps/
  CartSteps.java       <- things about shopping carts
  AccountSteps.java    <- registration, sign-in
  PaymentSteps.java    <- cards, refunds
  CommonSteps.java     <- genuinely shared, tiny

Rules of thumb:

  • Never create GivenSteps, WhenSteps, ThenSteps; related sentences end up in different files.
  • Keep sentences about the same noun together: a reader looking for "the cart total is..." should find it in CartSteps.
  • Put only very general steps in a CommonSteps class, and keep it small.
  • Steps in one class share instance fields; steps in different classes need a mechanism to share state, which is covered in the lesson on sharing state.

Kotlin

Cucumber-JVM works with Kotlin the same way; only the syntax changes (read-only):

Kotlin
package shop

import io.cucumber.java.en.Given
import io.cucumber.java.en.Then
import io.cucumber.java.en.When
import kotlin.test.assertEquals

class CartSteps {
    private var price = 0
    private var count = 0

    @Given("a book costing {int} dollars")
    fun aBookCostingDollars(p: Int) { price = p }

    @When("the customer adds {int} book(s)")
    fun theCustomerAddsBooks(n: Int) { count += n }

    @Then("the cart total is {int} dollars")
    fun theCartTotalIsDollars(expected: Int) = assertEquals(expected, price * count)
}

Kotlin allows backtick method names such as fun `the cart total is`(), but since Cucumber ignores method names this adds nothing; regular names keep stack traces readable.

Cucumber-JVM once offered lambda-style definitions through a separate cucumber-java8 module (Given("...", (Integer n) -> { ... })). That module is deprecated in modern releases, and the annotation style shown here is the recommended one.

Good step definitions

  • Short: three to ten lines. Anything longer belongs in a helper or page object.
  • Reusable: written for the sentence's meaning, so many scenarios use it.
  • Silent: no printing or sleeping; reports tell the story.
  • Honest names: the method name states what happens, even though Cucumber ignores it.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. How does Cucumber decide whether a step definition matches a sentence?

    The keyword is ignored; the text is matched against the expression in the annotation.
  2. 2. How does a step fail?

    Any exception thrown by the method fails the step; assertion libraries throw AssertionError.
  3. 3. Two different expressions both match one sentence. What happens?

    Ambiguity is an error; tighten one of the expressions.
  4. 4. How should you split a growing set of step definitions?

    Grouping by concept keeps related sentences together and easy to find.

Summary

  • A step definition is an annotated public method; the annotation holds the matching expression.
  • Cucumber discovers definitions by scanning the glue package with reflection and ignores keywords and method names when matching.
  • A step fails when it throws; use one assertion library, and only in Then steps.
  • Duplicate definitions abort start-up; ambiguous sentences fail the step and need tighter expressions.
  • Organize step classes by domain concept; Kotlin works the same way as Java.

Next: Cucumber Expressions