Skip to content
Tutorials Center
My learning

Topics

Lesson 23 of 29 ยท Real-world projects

Project: Test-Driven Bank Account

Build a bank account class with test-driven development: red, green, refactor with JUnit 6, exceptions, parameterized cases, edge cases and a transfer.

In this project you will build a small bank account the way many professionals build code: by writing the test first. You write a test for behavior that does not exist yet and watch it fail (red). You write the least code that makes it pass (green). Then you clean up with the tests as a safety net (refactor). Repeat in tiny steps.

Everything runs for real. Our Java runner has the JUnit 6 API, including parameterized tests, so each step is a runnable file. Keep the habits from Designing Good Tests in mind: behavior names, one behavior per test, fresh objects each time. For the theory of the cycle see Test-Driven Development in Advanced Java; here we just do it.

The plan

Red, green, refactor

Red Write a failing test first.
Green Make it pass with the simplest code.
Refactor Clean up while the tests stay green.

Each loop takes minutes, not hours.

1 / 2

We keep money in cents as a long. Floating-point numbers are the wrong tool for money (0.1 + 0.2 is not 0.3), and integers make the arithmetic exact. A real system would use a Money type or BigDecimal; the testing lessons are the same.

Step 1: red

We start with the first requirement: a new account has a balance, and a deposit increases it. Before writing the real class we write only enough to compile, a stub that does nothing. Then the tests. This is the "red" step: run it and make sure the tests fail for the right reason.

Java Step 1: failing tests against a stub

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.

One test passes by accident (a stub returning 0 matches "starts at zero"), and the other two fail with expected: <2500> but was: <0>. Good: they fail for the reason we expect, not because of a typo. That accidental pass is a reminder that a green test only means something if you have seen it go red for the right reason, which is why the first step in TDD is never skipped.

Step 2: green, then errors

Now we implement the simplest thing that works, and we add the next requirements as tests: withdrawals, and the errors. For errors we design the API first. A withdrawal larger than the balance throws a custom InsufficientFundsException that carries the numbers, and an amount that is not positive throws IllegalArgumentException.

For the "bad amounts" rule we use a parameterized test. One method runs several times with different inputs, so adding a case is one line, and each case is reported separately. @ValueSource supplies simple values; @CsvSource supplies several columns per case. (Parameterized tests get their own lesson, Parameterized and Dynamic Tests.)

Java Step 2: the account, exceptions and parameterized cases

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.

Look at what the tests pin down besides the happy path:

  • Boundaries. Withdrawing exactly the balance works (canWithdrawTheWholeBalance) and one cent more does not (overdrawIsRefused...). Boundary conditions are where < versus <= bugs live; try changing cents > balanceCents to >= in the class and the whole-balance test turns red at once.
  • No side effects on failure. The refused withdrawal leaves the balance untouched. A failure that corrupts state is a worse bug than the failure itself.
  • Data on the exception. The test reads balanceCents and requestedCents from the exception, so callers can show a helpful message without parsing text.
  • Parameterized names. @ParameterizedTest(name = "...") makes each row a readable sentence in the report.

Refactor

With everything green, look for small improvements. Both deposit and withdraw start with the same check, which we already pulled into requirePositive. If that had been duplicated, now is the time to merge it: change the production code, rerun, and the tests tell you immediately if you changed behavior. Refactoring without tests is guessing; refactoring with tests is a routine edit.

Step 3: a requirement that crosses accounts

The last requirement is a transfer: move money from one account to another, either completely or not at all. We write the tests first again. The interesting test is the failing one: if the source account lacks the money, neither balance may change. Our implementation does the withdraw first (it can throw), and only then the deposit, so an exception leaves both accounts as they were.

Java Step 3: transfers that are all or nothing

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 @Nested group shares the accounts of the outer class and gives the refusal rules a heading in the report. You will meet nesting properly in Lifecycle, Nested Tests and Display Names.

A real bank must also worry about two transfers happening at the same time, which needs locking or a database transaction and is beyond a unit test. A good practice here: write down what you have not tested. The class above is not thread-safe, and saying so in a comment or a test name (a skipped test named concurrentTransfersAreSafe with @Disabled("needs locking")) keeps the gap visible.

Where to go from here

Try these extensions, each as a new red-green loop:

  1. Transaction history. Record each deposit and withdrawal and test that history() returns them in order, unmodifiable from outside.
  2. Overdraft limit. Constructor takes a limit; test the exact boundary of -limit.
  3. Interest. applyInterest(rateBasisPoints) with rounding rules. Write the rounding rule as a table of parameterized cases first.
  4. A clock. Add timestamps using an injected Clock, as in Flaky Tests and Common Mistakes.
  5. Repeat it in TestNG with the same tests, to see how little changes (see Your First TestNG Test).

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. In test-driven development, what comes first?

    TDD starts red: a test that fails because the behavior is missing. You then write the simplest code that makes it pass.
  2. 2. Why does the project store money as a long number of cents?

    Binary floating point cannot represent values like 0.1 exactly. Whole cents in an integer type are exact.
  3. 3. What does the test overdrawIsRefusedAndBalanceIsUntouched check besides the exception type?

    After the refusal the test asserts that the balance still equals the starting value. A failed operation must not change state.
  4. 4. What is the advantage of @ParameterizedTest with @CsvSource for the remainder cases?

    One test method runs once per row, and the report lists each row separately, so failures point at the exact input.
  5. 5. In Bank.transfer, why is withdraw called before deposit?

    Putting the operation that can fail first means a failure leaves both accounts untouched, which is the all-or-nothing rule the tests demand.

Summary

  • Red, green, refactor: write a failing test, make it pass with the simplest code, then clean up under the protection of the tests.
  • Watch each new test fail for the right reason before you trust it; a stub can pass a test by accident.
  • Test boundaries (exactly the balance, one cent over), invalid inputs with @ParameterizedTest, and no side effects on failure.
  • Use assertThrows and read the exception's data instead of parsing its message.
  • Multi-object rules such as transfers are tested through their observable results: both balances, and the total.
  • Write down what is not tested (concurrency here) so the gap stays visible.
  • All three steps ran on the real JUnit 6 API; only the runner helper replaces your build tool.

Next: Project: Testing a Shopping Cart with Mocks, where a service talks to a repository and you test it with hand-made doubles.