Testing Swing Code
Problem
You want to write unit tests for Swing portions of your application.
Solution
Keep application logic separate from GUI layout, thus minimizing the need to test graphical code directly. Also, design your user interface in terms of discrete components that are testable without complex setup and configuration.
Discussion
Graphical code presents many testing challenges. For instance, many Swing functions only work when the components are visible on screen. In these cases, your tests have to create dummy frames and show the components before the tests can succeed. In other cases, Swing schedules events on the AWT event queue rather than updating component states immediately. We show how to tackle this issue in the next recipe.
Ideally, you should strive to minimize the need to test Swing code in
the first place. Application logic, such as computing the monthly
payment amount for a loan, should not be intertwined with the
JTable that displays the payment history. Instead,
you might want to define three separate classes:
-
Loan A utility class that keeps track of payments, interest rates, and other attributes. This class can be tested independently of Swing.
-
LoanPaymentTableModel A Swing table model for a history of loan payments. Because table models are nongraphical, you can test them just like any other Java class.
-
JTable Displays the
LoanPaymentTableModel. BecauseJTableis provided with Swing, you don’t have to test it.
There are more complex scenarios where you ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access