Course map
Stage 1: Foundation
Stage 2: Intermediate
Stage 3: Advanced
Stage 4: DSA in Java
Stage 5: Specialization

Part 10 / Topic 8 of 12

What to test (and what not to)

Not every line of code deserves its own test, and not every test is worth writing. A few rules that hold up in practice:

  • Test behaviour, not implementation. A test should survive you rewriting a method's internals, as long as its observable result does not change. withdraw_lessThanBalance_decreasesBalance checks getBalance() after a withdrawal — it does not care whether withdraw uses a for loop or a one-liner inside.
  • Test the edges, not just the middle. finalPrice(1000.0, 20.0) (a normal case) is less revealing than finalPrice(-500.0, ...) (negative price), finalPrice(1000.0, 150.0) (discount over 100%), or finalPrice(0.0, 20.0) (a zero bill) — bugs cluster at boundaries, not in the comfortable middle.
  • Test the errors you promised. If a method's contract is "throws IllegalArgumentException for a negative price," that promise is untested until a test actually triggers it and checks the exception type (and ideally the message, as Sections 5 and 6 both do).
  • One assertion focus per test. withdraw_moreThanBalance_throwsInsufficientFundsExceptionWithClearMessage checks one behaviour: the right exception, with the right message. It does not also check that a deposit afterward still works — that is a separate test, with its own name.
  • Don't test the JDK, or trivial getters. A test for getBalance() returning exactly what was stored by a constructor you also wrote is testing assignment, not logic — Section 6's BankAccountTest only calls getBalance() as a way to check the real behaviour (a deposit, a withdrawal), never on its own.
  • Don't test private details through reflection or hacks. If a test needs to reach into a class's private internals to make an assertion, the test is coupled to implementation, not behaviour — test through the public methods, the way every example in this part does.

Done here? The practice set for Part 10 — including the solutions — is on the part page.

Search the guide