Skip to content
Tutorials Center
My learning

Topics

Lesson 36 of 37 ยท Projects and Practice

Project: Build a Mini Gherkin Runner

Understand Cucumber by building a tiny version: parse Gherkin into scenarios, expand outlines, turn Cucumber expressions into regex, run hooks and tags, and print a report.

The best way to stop thinking of Cucumber as magic is to build a small one. In this project you will write a Gherkin runner in Java in about 150 lines. It parses feature text, expands outlines, resolves Cucumber-style expressions such as and , runs hooks with tag filters, executes steps and prints a report. It is not a replacement for the real tool, which supports many more features (data tables, doc strings, Rules, i18n, plugins, parallelism), but after this project the real tool's behavior will make sense.

The real Cucumber is not available on this site, so this stand-in runs on the Java runner. The project is split into parts: the model and parser, the expression compiler, hooks and tags, and the runner. Each part is shown as a snippet; the complete program is at the end.

What a runner does

Parse Text into features and scenarios.
Match Each step to one definition.
Run Hooks, steps, hooks.
Report Passed, failed, skipped.
1 / 2

Part 1: the model and the parser

A feature is a name plus scenarios. Each scenario has a name, a set of tags and a flat list of step texts. By giving the parser the job of expanding outlines and prepending the Background, the runner only ever sees plain scenarios, which keeps it simple. Real Cucumber also produces such a flat "pickle" per scenario; that is the term in its source code.

Java
record Scenario(String name, Set<String> tags, List<String> steps) {}
record Feature(String name, List<Scenario> scenarios) {}

The parser reads line by line. Tag lines are remembered until the next Feature, Scenario or Background. Lines that begin with a keyword (Given, When, Then, And, But) become steps of the current block. Table rows (| a | b |) belong to an outline's Examples. Everything else (comments, descriptions) is ignored. When a new block begins, the previous one is flushed: a plain scenario is added as is, a Background is stored, and an outline is expanded into one scenario per row, replacing <placeholders>.

Run the first example: it only parses, and prints the scenarios the runner would execute.

Java Part 1: parse and expand (Java)

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.

Note how the @shop tag on the Feature is inherited by every scenario, and @fast only by the first (Tags). The leading keyword is dropped from each step because Cucumber matches step text regardless of whether it began with Given, When or Then.

Part 2: compiling expressions

Step definitions in Cucumber-JVM use Cucumber expressions, such as the total is {int} dollars. The runner turns each into a regular expression: literal text is quoted, and each placeholder becomes a capture group.

Placeholder Regular expression
(-?\d+)
(-?\d+(?:\.\d+)?)
([^\s]+)
"([^"]*)" (the quotes are part of the match, the group excludes them)
Java
static Pattern compile(String expression) {
    Matcher m = Pattern.compile("\\{(int|float|word|string)\\}").matcher(expression);
    StringBuilder regex = new StringBuilder("^");
    int last = 0;
    while (m.find()) {
        regex.append(Pattern.quote(expression.substring(last, m.start())));
        regex.append(switch (m.group(1)) {
            case "int" -> "(-?\\d+)";
            case "float" -> "(-?\\d+(?:\\.\\d+)?)";
            case "word" -> "([^\\s]+)";
            default -> "\"([^\"]*)\"";
        });
        last = m.end();
    }
    regex.append(Pattern.quote(expression.substring(last))).append("$");
    return Pattern.compile(regex.toString());
}

Matching converts captured groups to typed arguments: becomes an int, and so on. Here we simply pass strings and let each step parse them.

Part 3: hooks and tag filters

A hook is a body, an order number and an optional tag. Before hooks run in ascending order, After hooks in descending order, and a hook with a tag only runs for scenarios that have it (Hooks). The scenario filter accepts a single tag, not tag, or null for everything.

Java
record Hook(int order, String tag, Runnable body) {}

static void runHooks(List<Hook> hooks, Set<String> tags, boolean ascending) {
    Comparator<Hook> by = Comparator.comparingInt(Hook::order);
    hooks.stream().sorted(ascending ? by : by.reversed())
         .filter(h -> h.tag() == null || tags.contains(h.tag()))
         .forEach(h -> h.body().run());
}

Part 4: the runner and the report

For each scenario: run Before hooks, run steps until one fails (the rest are skipped; an unmatched step is undefined), then always run After hooks. Finally print counts. This is exactly the life cycle from the how Cucumber works lesson, in code.

Java Part 4: the complete mini runner (Java)

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 report shows the usual states. The @fast hook appears only in the first scenario, the failing scenario skips its last step, and the undefined step is flagged instead of crashing the run.

What the real tool adds

  • Cucumber expressions with optional text (s), alternatives a/b and custom parameter types; regular expressions as an alternative.
  • Data tables and doc strings passed to steps, and Rule blocks.
  • Translations of keywords to over 70 languages.
  • Plugins and the message stream (Reports), dependency injection (State), parallel scenario execution (Parallel), and IDE integration.
  • Snippets for undefined steps, ready to paste.

Extension ideas

  1. Support And/But colouring in the output by remembering the previous keyword.
  2. Add tag expressions with and, or, not using the evaluator from the tags lesson.
  3. Support data tables: pass the rows beneath a step to the step body.
  4. Print a snippet for each undefined step, such as step("it sings", a -> {...});.
  5. Add @AfterStep-style hooks, and time each step.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why does the parser expand outlines and prepend the Background?

    A flat list of steps per scenario keeps the runner simple. Real Cucumber does the same when it builds pickles.
  2. 2. What happens to steps after a failed step in the runner?

    Once a step fails, remaining steps are skipped, like Cucumber.
  3. 3. How does the runner turn a Cucumber expression into a regular expression?

    Literal text is escaped and placeholders like {int} become groups such as (-?\d+).
  4. 4. In which order do After hooks with order 10 and 20 run?

    After hooks run in descending order, mirroring the Before order.

Summary

  • A Gherkin runner parses, expands, matches, runs and reports; everything else is extra.
  • Compile Cucumber expressions into regular expressions with capture groups.
  • Hooks run in order around each scenario; After hooks always run, in reverse.
  • Building the tool yourself makes undefined, pending, skipped and failed states obvious.

Next: Practice exercises and review