A class with state: check the balance after each action

level 2 · 20 min · state and error testing

A pure function returns the result and that is it. A class keeps state: what an action does only shows up later, when you ask. That is why the test has three steps: set up the object, act and check the state through what the class exposes, here getBalance().

Errors call for two precautions. The first is to check the exact message: a test that only expects “some error” approves the wrong error. The second is to check the state after the refusal: a refused action must not have touched anything.

Rule of thumb. Set up, act and check the state. For each error, check the exact message and, after it, that the state is unchanged.

Explore the rule

The BankAccount class starts with a balance of 100. Make deposits and withdrawals, including the ones the contract refuses, and watch the balance.

Balance: 100

Choose an operation. The account starts at 100.

Deposit and withdraw need an amount greater than 0. Withdrawing more than the balance is refused; withdrawing the whole balance is not.

Exercise: write the tests

Your tests must pass on the correct code and fail on the 5 planted bugs.

Write tests for the BankAccount class described in the contract. Five broken versions are waiting.

Check state through getBalance() after each action, check that invalid actions throw the documented message, and check that a failed action leaves the balance untouched.

class BankAccount {
  /** Starts with the given balance (default 0). */
  constructor(initialBalance = 0)

  /** Adds a positive amount. Throws Error("Amount must be positive") for 0 or less. */
  deposit(amount)

  /**
   * Removes a positive amount. Throws Error("Amount must be positive") for 0 or less,
   * and Error("Insufficient funds") when amount is more than the balance.
   * Withdrawing the whole balance is allowed.
   */
  withdraw(amount)

  /** Current balance. */
  getBalance()
}

Coverage radar: ranges and limits your tests already touch

  • An account that starts with a balance: not yet
  • A deposit of 0 or less: not yet
  • Withdrawing the whole balance: not yet
  • A withdrawal larger than the balance, with the exact message: not yet
  • The balance checked after a refused operation: not yet

Your tests

0 of 5 bugs detected

  • Bug 1: hidden
  • Bug 2: hidden
  • Bug 3: hidden
  • Bug 4: hidden
  • Bug 5: hidden

References

  • ISTQB® Certified Tester Foundation Level v4.0, section 2.1, Testing in the Context of a Software Development Lifecycle. © ISTQB®.