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_decreasesBalancechecksgetBalance()after a withdrawal — it does not care whetherwithdrawuses aforloop or a one-liner inside. - Test the edges, not just the middle.
finalPrice(1000.0, 20.0)(a normal case) is less revealing thanfinalPrice(-500.0, ...)(negative price),finalPrice(1000.0, 150.0)(discount over 100%), orfinalPrice(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
IllegalArgumentExceptionfor 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_throwsInsufficientFundsExceptionWithClearMessagechecks 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'sBankAccountTestonly callsgetBalance()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.