Skip to main content

Hello World

The smallest possible SpecBinder example. A single scenario with plain steps — no parameters, no rules, no configuration.

Source: examples/getting-started/example-1 on GitHub.

What this demonstrates​

  • Minimal setup: one marker class, one .feature file and one test class
  • How @Gherkin2JUnit("path") triggers code generation
  • Given / When / Then steps become method calls in the generated test class
  • Each step becomes an abstract method in the generated class — you implement it in a concrete subclass
  • The marker class stays empty; a step left unimplemented is a compile error

The feature file​

src/test/resources/specs/ShoppingCart.feature
Feature: ShoppingCart

As a shopper
I want to add items to my cart
So that I can see everything I picked before I pay

Scenario: Add a single item to an empty cart
Given I have an empty shopping cart
When I add an item to the cart
Then the cart should contain one item

The marker class​

ShoppingCartFeature.java
package dev.specbinder.examples.gettingstarted.helloworld;

import dev.specbinder.annotations.Gherkin2JUnit;

@Gherkin2JUnit("specs/ShoppingCart.feature")
public abstract class ShoppingCartFeature {
}

The generated test class​

After compilation, the processor writes ShoppingCartScenarios.java to target/generated-test-sources/:

target/generated-test-sources/.../ShoppingCartScenarios.java
public abstract class ShoppingCartScenarios extends ShoppingCartFeature {

public abstract void iHaveAnEmptyShoppingCart();

public abstract void iAddAnItemToTheCart();

public abstract void theCartShouldContainOneItem();

@Test
@DisplayName("Scenario: Add a single item to an empty cart")
public void scenario_1() {
/*
* Given I have an empty shopping cart
*/
iHaveAnEmptyShoppingCart();
/*
* When I add an item to the cart
*/
iAddAnItemToTheCart();
/*
* Then the cart should contain one item
*/
theCartShouldContainOneItem();
}
}

By default, the generated class is abstract with one abstract method per step. JUnit never runs an abstract class, so the last piece is a concrete subclass.

The test class​

ShoppingCartTest.java
public class ShoppingCartTest extends ShoppingCartScenarios {

private final List<String> cart = new ArrayList<>();

@Override
public void iHaveAnEmptyShoppingCart() {
cart.clear();
}

@Override
public void iAddAnItemToTheCart() {
cart.add("Wireless Headphones");
}

@Override
public void theCartShouldContainOneItem() {
assertEquals(1, cart.size());
}
}

ShoppingCartTest is the class JUnit runs. Leave one of the three methods out and it no longer compiles — the spec and the code can't drift apart silently.

ShoppingCartFeature.java          (marker class, @Gherkin2JUnit)
└→ ShoppingCartScenarios.java (generated, abstract — one abstract method per step)
└→ ShoppingCartTest.java (your concrete class, implements the step methods)

Run it​

cd examples/getting-started/example-1
mvn test