If you've been coding in Java for awhile, you know how to write a method to test equality. Why write tests for something you can code in your sleep? Because, as Jeff Langr points out, you've probably made plenty of dumb mistakes in your career, either while asleep or while wide awake. It's simpler and safer to just think of tests as specifications that you always have to code.

From the author of

From the author of

All Things Tested Equally

In part 1 of this series, we created Deck and Card classes
via tests. The starter test for the Deck class involved verifying that
a deck contained 52 cards, and that the deck indeed contained each card as
expected.

Listing 1 shows the test method from the DeckTest class we built
last time. For each iteration through the dual-loop series, the test calls the
contains method against the Deck object, passing in the
current rank and suit.

A better solution would be to implement the equals method on the
Card class. Once we define equality for two cards, we can have the
contains method simply delegate to the cards’
ArrayList.

We’ll tackle creating the equality method in two parts. In the first
part, we’ll build the equality method incrementally by virtue of simple,
sensible assertions. In the second part, we’ll ensure that it adheres to
the contract for equality, as laid out in the Javadoc for the Object
method equals.