Crafting Java with Test-Driven Development, Part 7: Adding Some Bulk
Building and Testing "Critical Mass"
In our last installment, we started building support into the Texas Hold ’Em application for the actual game. We got to the point of proving that we could deal hole cards to players.
In an attempt to get a bit of critical mass built into the application, I coded about an hours’ worth of test and code since our last installment. I’m going to expect you to be willing to go forward with this code, but we’ll want to make sure that you have a good understanding of it first.
The bulk of changes I made were driven by tests in GameTest. The complete source for GameTest is shown in Listing 1.
Listing 1 GameTest.
package domain; import junit.framework.*; public class GameTest extends TestCase { private static final int BURN = 1; private Game game; private Deck deck; private Player player1; private Player player2; private Player player3; private static final int STAKE = 1000; private static final int SMALL = 10; private static final int BIG = 20; protected void setUp() { game = new Game(); game.setBlinds(SMALL, BIG); deck = game.deck(); player1 = new Player("a"); player1.add(STAKE); player2 = new Player("b"); player2.add(STAKE); player3 = new Player("c"); player3.add(STAKE); } public void testCreate() { assertPlayers(); } public void testAddSinglePlayer() { final String name = "Jeff"; game.add(new Player(name)); assertPlayers(name); } public void testAddMaximumNumberOfPlayers() { for (int i = 0; i < Game.CAPACITY; i++) game.add(new Player("" + i)); assertPlayers("0", "1", "2", "3", "4", "5", "6", "7", "8", "9"); } public void testDealCompleteHand() { addTwoPlayers(); game.setButton(2); game.startHand(); Card[] hole = deck.top(4); game.dealHoleCards(); assertHoleCards(player1, hole, 0, 2); assertHoleCards(player2, hole, 1, 3); int remaining = Deck.SIZE - hole.length; assertEquals(remaining, deck.cardsRemaining()); Card[] flop = deck.top(BURN + 3); game.dealFlop(); remaining -= flop.length; assertCardsDealt(remaining, flop); CardTest.assertCards( game.community(), flop[1], flop[2], flop[3]); Card[] turn = deck.top(BURN + 1); game.dealTurn(); remaining -= turn.length; assertCardsDealt(remaining, turn); CardTest.assertCards( game.community(), flop[1], flop[2], flop[3], turn[1]); Card[] river = deck.top(BURN + 1); game.dealRiver(); remaining -= river.length; assertCardsDealt(remaining, river); CardTest.assertCards(game.community(), flop[1], flop[2], flop[3], turn[1], river[1]); } public void testDealOrderStartsFromButton() { addTwoPlayers(); game.setButton(1); game.startHand(); Card[] hole = deck.top(4); dealAllCardsInHand(); assertHoleCards(player1, hole, 1, 3); assertHoleCards(player2, hole, 0, 2); game.stopHand(); game.startHand(); hole = deck.top(4); dealAllCardsInHand(); assertHoleCards(player1, hole, 0, 2); assertHoleCards(player2, hole, 1, 3); } public void testBlinds() { addThreePlayers(); game.setButton(3); game.startHand(); assertEquals(STAKE - SMALL, player1.chipCount()); assertEquals(STAKE - BIG, player2.chipCount()); assertEquals(STAKE, player3.chipCount()); } public void testHandFlow() { addThreePlayers(); game.setButton(3); game.startHand(); dealAllCardsInHand(); game.stopHand(); assertEquals(1, game.buttonPosition()); assertNoCardsOut(); game.startHand(); dealAllCardsInHand(); game.stopHand(); assertEquals(2, game.buttonPosition()); assertNoCardsOut(); game.startHand(); dealAllCardsInHand(); game.stopHand(); assertEquals(3, game.buttonPosition()); assertNoCardsOut(); fail("need to ensure blinds are extracted properly"); } // missing tests: // - use a new deck each time! private void assertNoCardsOut() { for (Player player: game.players()) assertTrue(player.holeCards().isEmpty()); assertTrue(game.community().isEmpty()); } private void dealAllCardsInHand() { game.dealHoleCards(); game.dealFlop(); game.dealTurn(); game.dealRiver(); } private void addThreePlayers() { game.add(player1); game.add(player2); game.add(player3); } private void addTwoPlayers() { game.add(player1); game.add(player2); } private void assertCardsDealt(int remaining, Card[] turn) { assertDeckCount(remaining); DeckTest.assertCardsDealt(deck, turn); } private void assertHoleCards( Player player, Card[] hole, int... indices) { Card[] cards = new Card[indices.length]; for (int i = 0; i < indices.length; i++) cards[i] = hole[indices[i]]; DeckTest.assertCardsDealt(deck, cards); CardTest.assertCards(player.holeCards(), cards); } private void assertDeckCount(int expected) { assertEquals(expected, deck.cardsRemaining()); } private void assertPlayers(String... expected) { assertEquals(expected.length, game.players().size()); int i = 0; for (Player player : game.players()) assertEquals(expected[i++], player.getName()); } }
Let’s step through each of the tests and see what we have.
- testCreate, testAddSinglePlayer, testAddMaximumNumberOfPlayers: These three tests remain unchanged from what we built in the last installment.
- testDealCompleteHand: This test grew out of
testDealHoleCards, which we started in the last installment. The idea
of this test is to demonstrate that cards are dealt properly to all players
within a single Texas Hold ’Em hand. Paraphrased, the test says the
following:
- Add two players to the game.
- Set the button to the second (last) player. This means that dealing starts from the first player.
- Start the hand. This implies that a new deck is ready and shuffled.
- Peek at the top four cards from the deck, so that we have a way of verifying the actual hole cards that get dealt. A Texas Hold ’Em hand starts with two cards dealt to each player in turn, starting with the player to the left of the button. The ability to peek at cards is a testing need that required some changes to the Deck class. We’ll review these changes shortly.
- Deal the hole cards. We call assertHoleCards twice, to verify that player 1 received the first (0th, using Java’s zero-based indexing) and third cards dealt and player 2 received the second and fourth cards dealt. We also verify that 48 cards remain in the deck.
- Peek at the top four cards, representing a burn plus the flop. The flop is three community cards—they are dealt face-up at the center of the table. Prior to dealing the flop, the dealer must "burn" (discard) a card, per Texas Hold ’Em dealing convention.
- Deal the flop. Similar to the way we verified the hole cards, we compare the community cards against the cards we peeked. We also verify the number of cards remaining in the deck.
- Peek at the next two cards, representing a burn and the "turn." The turn is the fourth community card dealt. We compare the turn to the result of calling dealTurn against the Game object. We also verify the number of cards remaining in the deck.
- Peek at the next two cards, representing a burn and the "river." The river is the fifth and final community card dealt. We compare the river to the result of calling dealRiver against the Game object. We also verify the number of cards remaining in the deck.
The DeckTest method assertCardsDealt originally started in GameTest. It makes more sense on the DeckTest class, since it deals with a deck and cards, but knows nothing about a game. Here’s what it looks like:
public static void assertCardsDealt(Deck deck, Card... cards) { for (Card card: cards) assertFalse(deck.contains(card.getRank(), card.getSuit())); }
The method assertCards in CardTest originally came from PlayerTest. I changed assertCards to be a static method so that other tests could use it. Here’s what it looks like now:
public static void assertCards(List<Card> cards, Card... expected) { assertEquals(expected.length, cards.size()); int i = 0; for (Card card: expected) assertEquals(card, cards.get(i++)); }
Test code in GameTest needs the capability to look at cards in the deck without dealing them. This means that our Deck class needed to change. Listing 2 shows a couple of tests in DeckTest that drove out support for peeking.
Listing 2 Testing the ability to peek in DeckTest.
// seeing the top card is very valuable in testing public void testTop() { Card top = deck1.top(); assertEquals(Deck.SIZE, deck1.cardsRemaining()); Card card = deck1.deal(); assertEquals(top, card); } // seeing the top N cards is very valuable in testing public void testTopN() { Card[] top = deck1.top(3); assertEquals(Deck.SIZE, deck1.cardsRemaining()); assertEquals(3, top.length); assertEquals(top[0], deck1.deal()); assertEquals(top[1], deck1.deal()); assertEquals(top[2], deck1.deal()); }
These two "top" tests resulted in the production methods in Deck shown in Listing 3.
Listing 3 Peek code in Deck.
// primarily used for testing Card top() { return cards.get(0); } // primarily used for testing public Card[] top(int count) { Card[] results = new Card[count]; for (int i = 0; i < count; i++) results[i] = cards.get(i); return results; }
Let’s step through each of the tests.
- testHandFlow: In Texas Hold ’Em, one hand is almost never the entire game. It results in one player winning the pot, to which that player and others contributed during the course of the hand. Once the pot is won, a new hand begins. The purpose of testHandFlow is to demonstrate the game flow from hand to hand. We show that the button moves upon completion of each hand. Also, at the end of a hand, we show that no cards should be outstanding—no players should hold any cards, and the community should contain no cards. Note the fail method call at the very end of the test. We’ll discuss why this call exists later in this installment.
- testDealOrderStartsFromButton: This test verifies that the player to the left of the button receives the first hole card. It does so by dealing two hands, and verifying that the deal moves appropriately with each hand.
- testBlinds: In order to promote more betting action in each hand, Texas Hold ’Em requires that blinds be posted by the two players to the left of the button. Blinds are preset chip amounts. The player to the left of the button is known as the small blind; the second player in line is the big blind. Usually, but not always, the small blind is half of the big blind. Our setUp method sets the blinds:
game.setBlinds(SMALL, BIG);
The code in testBlinds starts a hand by calling startHand. It then verifies that each player’s chip count was appropriately decremented (or not). The code in this test required changes to the Player class to manage chips. We’ll review these changes later in this installment.
The production Game code appears in Listing 4.
Listing 4 Production Game code.
package domain; import java.util.*; public class Game { public static final int CAPACITY = 10; private List<Player> players = new ArrayList<Player>(); private List<Card> community = new ArrayList<Card>(); private Deck deck = new Deck(); private int button = 1; private int smallAmount; private int bigAmount; public List<Player> players() { return players; } public void dealHoleCards() { for (int round = 0; round < 2; round++) { int dealer = button + 1; for (int position = dealer; position < dealer + players.size(); position++) { Player player = getPlayer(position); player.dealToHole(deck.deal()); } } } public void add(Player player) { players.add(player); } // needed for testing Deck deck() { return deck; } public void dealFlop() { burn(); for (int i = 0; i < 3; i++) community.add(deck.deal()); } private void burn() { deck.deal(); } public List<Card> community() { return community; } public void dealTurn() { burnAndTurn(); } public void dealRiver() { burnAndTurn(); } private void burnAndTurn() { burn(); community.add(deck.deal()); } public void setButton(int i) { button = i; } public void setBlinds(int small, int big) { this.smallAmount = small; this.bigAmount = big; } public void startHand() { collectBlinds(); } private void collectBlinds() { Player small = getPlayer(button + 1); Player big = getPlayer(button + 2); small.bet(smallAmount); big.bet(bigAmount); } public int buttonPosition() { return button; } public void stopHand() { removeAllCards(); advanceButton(); } private void removeAllCards() { for (Player player: players()) player.removeCards(); community.clear(); } private void advanceButton() { button++; if (button > players.size()) button = 1; } private Player getPlayer(int position) { int index = position - 1; if (position > players.size()) index -= players.size(); return players.get(index); } }
The Game class is starting to do way too much. It’s managing both the flow of the game from hand to hand as well as the hand itself. That description suggests violation of the single-responsibility principle, a good class-design guideline that says classes should have one reason to change. We’ll do something about this design concern in an upcoming installment.
The methods advanceButton and getPlayer have some duplicate concepts. One significant key to keeping your system clean through refactoring is to recognize duplication where it may not be obvious. Here, both methods have logic that deals with finding the next position in the ring of players. Refactoring them resulted in the slightly cleaner code shown in Listing 5. I think the dealHoleCards method is now much easier to follow.
Listing 5 Refactored Game code.
public void dealHoleCards() { for (int round = 0; round < 2; round++) { for (int i = 1; i <= players.size(); i++) { Player player = getPlayer(button + i); player.dealToHole(deck.deal()); } } } private void advanceButton() { button = ringPosition(button + 1); } private int ringPosition(int position) { if (position > players.size()) return position - players.size(); return position; } private Player getPlayer(int position) { return players.get(ringPosition(position) - 1); }
The changes to Player were minor. In addition to the changes need to manage the player’s bankroll (chips), we need the ability to remove cards from each Player:
public void testRemoveCards() { player.dealToHole(CardTest.CARD1); player.dealToHole(CardTest.CARD2); player.removeCards(); assertTrue(player.holeCards().isEmpty()); }
The implementation for Player.removeCards is trivial. (Remember that the code for each installment of this series is always available for download.)
A couple of tests in PlayerTest show how we manage a player’s chips (see Listing 6). The production code resulting from those two tests is shown in Listing 7.
Listing 6 PlayerTest.
public void testBankroll() { assertEquals(0, player.chipCount()); player.add(1000); assertEquals(1000, player.chipCount()); player.bet(200); assertEquals(800, player.chipCount()); } public void testInsufficientFunds() { try { player.bet(1); fail("expected insuff. funds exception"); } catch (InsufficientFundsException expected) { assertEquals(0, player.chipCount()); } }
Listing 7 Player.
public class Player { ... private int chips = 0; ... public int chipCount() { return chips; } public void add(int amount) { chips += amount; } public void bet(int amount) { if (amount > chips) throw new InsufficientFundsException(); chips -= amount; } }
InsufficientFundsException is simply a RuntimeException subclass.
You might want to look further through the rest of the code. I made some minor refactorings for clarity and organizational reasons.