Testing Behavior Versus Testing Methods

When you write tests, focus on the behaviors of your class, not on testing the individual methods.

To understand what that means, think about the tedious but time-tested example of an ATM class for a banking system. Its methods include deposit(), withdraw(), and getBalance(). We might start with the following tests:

  • makeSingleDeposit

  • makeMultipleDeposits

To verify the results of each of those tests, you need to call getBalance(). Yet you probably don’t want a test that focuses on verifying the getBalance() method. Its behavior is probably uninteresting (it likely just returns a field). Any interesting behavior requires other operations to occur first—namely, deposits and withdrawals. So let’s look at ...

Get Pragmatic Unit Testing in Java 8 with JUnit now with the O’Reilly learning platform.

O’Reilly members experience live online training, plus books, videos, and digital content from nearly 200 publishers.