- The Series
- Lets Go!
- Testing the Decks Contents
- Next: Testing Equality
Testing the Deck’s Contents
The test for deck instantiation only demonstrates that a new deck contains the correct number of cards. A complete test needs to prove the contents of the deck. A poker deck contains 13 ranked cards of each suit (hearts, diamonds, clubs, spades). Cards rank in increasing order from 2 through 10, followed by jack, queen, king, and ace.
I can represent each card in the deck as a simple data object. A card contains a rank and suit, each of which is expressed as an enum value.
Listings 8 through 11 show all the bits at this point.
Listing 8 CardTest.
package domain; import junit.framework.*; public class CardTest extends TestCase { public void testCreate() { Card card = new Card(Rank.ace, Suit.clubs); assertEquals(Rank.ace, card.getRank()); assertEquals(Suit.clubs, card.getSuit()); } }
Listing 9 Card.
package domain; public class Card { private Rank rank; private Suit suit; public Card(Rank rank, Suit suit) { this.rank = rank; this.suit = suit; } public Rank getRank() { return rank; } public Suit getSuit() { return suit; } }
Listing 10 Rank.
package domain; public enum Rank { two, three, four, five, six, seven, eight, nine, ten, jack, queen, king, ace }
Listing 11 Suit.
package domain; public enum Suit { hearts, diamonds, clubs, spades }
I created no tests for the enums—they have no behavior!
I expanded my creation test in Deck to verify a new deck’s contents. The test now loops through all possible cards in the deck, ensuring that the deck object contains each. Code in DeckTest uses another form of assertion method, assertTrue (see Listing 12). The assertTrue method simply takes a Boolean argument and fails the test if the argument value is false. Listing 13 shows the latest version of Deck.
Listing 12 assertTrue method in DeckTest.
package domain; import junit.framework.*; public class DeckTest extends TestCase { public void testCreate() { Deck deck = new Deck(); assertEquals(Deck.SIZE, deck.cardsRemaining()); for (Suit suit: Suit.values()) for (Rank rank: Rank.values()) assertTrue(deck.contains(rank, suit)); } }
Listing 13 Working version of Deck.
package domain; import java.util.*; public class Deck { public static final int SIZE = 52; private List<Card> cards = new ArrayList<Card>(); public Deck() { for (Suit suit: Suit.values()) for (Rank rank: Rank.values()) cards.add(new Card(rank, suit)); } public int cardsRemaining() { return SIZE; } public boolean contains(Rank rank, Suit suit) { for (Card card: cards) if (rank == card.getRank() && suit == card.getSuit()) return true; return false; } }