Skip to content
Tutorials Center
My learning

Topics

Lesson 34 of 37 ยท Projects and Practice

Project: Bank Account Behavior

Build a bank account feature test-first: discover rules, write Gherkin with scenario outlines, run it in a Java mini runner, then see the matching real Cucumber-JVM glue.

In this project you will drive a small feature the BDD way: start from the rules, write scenarios, watch them fail, then make them pass. The feature is a bank account with deposits, withdrawals and an overdraft limit. It is small enough to finish in an hour but rich enough to need rules, examples, error cases and a table of data.

Cucumber cannot run on this site, so we use a mini runner written in Java: it reads real Gherkin text, matches each step against regular expressions and prints a result like a console report. The domain code and step definitions have the same shape as real Cucumber-JVM glue, and at the end you will see the real annotations next to them.

Step 1: discover the rules

Imagine the three amigos conversation (Three amigos). The product owner says: "Customers can pay money in and take money out, but not below zero. Some accounts have an overdraft." The tester asks what happens at exactly zero, and whether a rejected withdrawal changes the balance. The developer asks whether a deposit of zero is allowed. You write down the rules and examples:

Rule Examples
A deposit increases the balance 100 + 50 = 150
A withdrawal decreases the balance 100 - 30 = 70
A withdrawal may not take the balance below the overdraft limit 100 - 100 = 0 allowed; 100 - 101 rejected with "Insufficient funds"; with an overdraft of 50, 100 - 150 allowed
A rejected withdrawal leaves the balance unchanged still 100 after a rejected 101
Amounts must be positive deposit of 0 rejected with "Amount must be positive"

Step 2: write the feature

GHERKIN
Feature: Bank account
  Customers pay money in and take it out, within an agreed overdraft.

  Scenario: A deposit increases the balance
    Given an account with a balance of 100 dollars
    When I deposit 50 dollars
    Then the balance is 150 dollars

  Scenario: A withdrawal decreases the balance
    Given an account with a balance of 100 dollars
    When I withdraw 30 dollars
    Then the balance is 70 dollars

  Scenario: Withdrawing the whole balance is allowed
    Given an account with a balance of 100 dollars
    When I withdraw 100 dollars
    Then the balance is 0 dollars

  Scenario: Withdrawing too much is rejected
    Given an account with a balance of 100 dollars
    When I withdraw 101 dollars
    Then the request is rejected with "Insufficient funds"
    And the balance is 100 dollars

  Scenario: An overdraft allows a negative balance
    Given an account with a balance of 100 dollars and an overdraft of 50 dollars
    When I withdraw 150 dollars
    Then the balance is -50 dollars

  Scenario: Amounts must be positive
    Given an account with a balance of 100 dollars
    When I deposit 0 dollars
    Then the request is rejected with "Amount must be positive"

Each scenario names one behavior and has three or four steps, using the declarative style from earlier in this chapter.

Step 3: run it in the mini runner

The program below contains the feature text, a BankAccount class (the "code under test"), step definitions as regular expressions with capture groups (like Cucumber expressions compile to) and a small runner. Press Run. Everything should pass.

Java Bank account feature with a 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.

Step 4: see red first

BDD works best when you watch a scenario fail before it passes. Change BankAccount.withdraw so that it ignores the overdraft (replace -overdraft with 0) and run again. The "overdraft" scenario fails at the When step, and the runner names the step and skips the rest. Restore the line to go green. In real Cucumber, an unmatched step is reported as undefined and a missing implementation can be marked PendingException, which is a handy way to write the Gherkin first and the code later.

The real Cucumber-JVM glue

The step definitions above translate almost line by line into real glue. This is read-only because Cucumber is not available here.

Java
package bank.steps;

import io.cucumber.java.en.*;
import static org.junit.jupiter.api.Assertions.*;

public class AccountSteps {
    private final BankWorld world;

    public AccountSteps(BankWorld world) { this.world = world; }   // injected, one per scenario

    @Given("an account with a balance of {int} dollars")
    public void account(int balance) {
        world.account = new BankAccount(balance, 0);
    }

    @Given("an account with a balance of {int} dollars and an overdraft of {int} dollars")
    public void accountWithOverdraft(int balance, int overdraft) {
        world.account = new BankAccount(balance, overdraft);
    }

    @When("I deposit {int} dollars")
    public void deposit(int amount) {
        world.attempt(() -> world.account.deposit(amount));
    }

    @When("I withdraw {int} dollars")
    public void withdraw(int amount) {
        world.attempt(() -> world.account.withdraw(amount));
    }

    @Then("the balance is {int} dollars")
    public void balance(int expected) {
        assertEquals(expected, world.account.balance());
    }

    @Then("the request is rejected with {string}")
    public void rejected(String message) {
        assertNotNull(world.error, "expected a rejection");
        assertEquals(message, world.error);
    }
}

Differences to notice: and Cucumber expressions replace the regular expressions (negative numbers work with ); the world is injected instead of static fields (Scenario state); and assertions come from JUnit.

Step 5: add data with a Scenario Outline

Six near-identical scenarios for withdrawals would be noisy. A table is better:

GHERKIN
Scenario Outline: Withdrawals against a balance and an overdraft
  Given an account with a balance of <balance> dollars and an overdraft of <overdraft> dollars
  When I withdraw <amount> dollars
  Then the balance is <result> dollars

  Examples:
    | balance | overdraft | amount | result |
    | 100     | 0         | 100    | 0      |
    | 100     | 50        | 150    | -50    |
    | 0       | 0         | 1      | rejected |

The last row exposes a design question: its Then step differs. Splitting rejected cases into their own outline keeps each table to one kind of outcome.

Extension ideas

  1. Add a transfer between two accounts, with a rule that a failed transfer changes neither balance.
  2. Add a daily withdrawal limit, and make the clock injectable (Test data).
  3. Tag scenarios @smoke, @rules and @validation, and select them with the tag evaluator from Tags.
  4. Add an @After that prints the final balance when a scenario fails (Hooks).

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. Why write the rules and examples table before the Gherkin?

    Discovering examples first reveals missing rules and boundary cases before any code exists.
  2. 2. What does the runner do with the steps after a failed step?

    Like Cucumber, later steps are skipped once a step fails.
  3. 3. Which Cucumber expression matches a negative whole number?

    {int} accepts optional signs, so -50 matches.
  4. 4. In the real glue, how is BankWorld shared between step classes?

    Dependency injection supplies one world per scenario to each class that asks for it.

Summary

  • Start from rules and examples, then write short declarative scenarios.
  • Run them red first, then make them green; undefined and pending steps are useful signals.
  • Real glue uses Cucumber expressions, injected state and JUnit assertions.
  • Scenario Outlines with tables handle many similar examples, one outcome type per table.

Next: Project: shopping cart