While developing a Java desktop application with Swing, I encountered the need to test the UI directly, and not just the underlying controller/model classes via unit tests.
This answer (on "What is the best testing tool for Swing-based applications?") suggested using FEST, which is unfortunately discontinued. However, there are a few projects that continued from where FEST left of. One in particular (mentioned in this answer) caught my attention, as I used it before in unit tests: AssertJ.
Apparently there is AssertJ Swing, which is based on FEST and offers some easy to use ways of writing your Swing UI tests. But still, getting to an initial/working setup is cumbersome as it's hard to say where to start.
How do I create a minimal test setup for the following example UI, consisting of only two classes?
Constraints: Java SE, Swing UI, Maven Project, JUnit
public class MainApp {
/**
* Run me, to use the app yourself.
*
* @param args ignored
*/
public static void main(String[] args) {
MainApp.showWindow().setSize(600, 600);
}
/**
* Internal standard method to initialize the view, returning the main JFrame (also to be used in automated tests).
*
* @return initialized JFrame instance
*/
public static MainWindow showWindow() {
MainWindow mainWindow = new MainWindow();
mainWindow.setVisible(true);
return mainWindow;
}
}
public class MainWindow extends JFrame {
public MainWindow() {
super("MainWindow");
this.setContentPane(this.createContentPane());
}
private JPanel createContentPane() {
JTextArea centerArea = new JTextArea();
centerArea.setName("Center-Area");
centerArea.setEditable(false);
JButton northButton = this.createButton("North", centerArea);
JButton southButton = this.createButton("South", centerArea);
JPanel contentPane = new JPanel(new BorderLayout());
contentPane.add(centerArea);
contentPane.add(northButton, BorderLayout.NORTH);
contentPane.add(southButton, BorderLayout.SOUTH);
return contentPane;
}
private JButton createButton(final String text, final JTextArea centerArea) {
JButton button = new JButton(text);
button.addActionListener(new ActionListener() {
@Override
public void actionPerformed(ActionEvent event) {
centerArea.setText(centerArea.getText() + text + ", ");
}
});
return button;
}
}
I'm aware that the question itself is very broad, therefore I provide an answer myself - show-casing this particular example.