Crafting Java with Test-Driven Development, Part 9: Driving a User Interface
Testing (and Punting) in Swing
We’ve designed and built a number of classes in our Texas Hold ’Em application: Card, Deck, Hand, Game, Ring, and Player. Among other activities, we can now deal hands to players, move the button, and collect blinds.
In this installment, I was thinking that we should work on adding betting support to the Hand and Game classes. But our customer—who, after all, is driving the requirements for the application—wants to see something "real." Real feedback to a customer means seeing a user interface of some sort. Showing customers green bars in JUnit isn’t enough to make them happy. The betting code is important, sure, but they’d rather start getting visual feedback first.
It looks like we’ll have to come back to betting support later. For this installment, we’ll build a Swing user interface to demonstrate how we deal hands to players. Test-first, of course.
Most programmers don’t find Swing programming to be very difficult. Tedious, yes; difficult, no. But they often claim that automating tests for Swing classes is difficult. Indeed, some things can be tricky to test when you build a robust user interface. The typical reaction is to punt: Swing is too hard to test, so we don’t test. "I don’t have to write tests for Swing code" becomes the excuse. As use of the excuse grows, so does the amount of code in the Swing classes. As the amount of code in the Swing classes grows, so does the number of defects in said code.
Sometimes logic creeps into a Swing class because that seems to be the most sensible place to put it, but my cynicism leads me to believe that logic creeps into Swing classes because programmers believe they don’t have to write tests for Swing code.
We will learn how to write tests for Swing code, but we want to make sure that we’re writing tests for the right reasons:
- Improving design
- Improving the ability to add new features to the code
- Minimizing defects
- Documenting class capabilities
- Improving overall confidence in the system
Occasionally, even we will punt. Layout is one thing we won’t test—it’s pretty tough to automate tests to ensure that something looks aesthetically pleasing. We’ll need to visually inspect layout.