在使用 Swing 开发 Java 桌面应用程序时,我需要直接测试 UI,而不仅仅是通过单元测试测试底层控制器/模型类。
This 答案(关于“基于 Swing 的应用程序的最佳测试工具是什么?”) https://stackoverflow.com/a/80222/5127499建议使用FEST https://code.google.com/archive/p/fest/,不幸的是已经停产了。
然而,有一些项目是从 FEST 离开的地方继续进行的。特别是其中一个(在本节中提到answer https://stackoverflow.com/questions/91179/automated-tests-for-java-swing-guis/32771043)引起了我的注意,因为我之前在单元测试中使用过它:AssertJ https://joel-costigliola.github.io/assertj/.
显然有断言J Swing https://joel-costigliola.github.io/assertj/assertj-swing.html,它基于 FEST,并提供了一些编写 Swing UI 测试的易于使用的方法。
但是,进行初始/工作设置仍然很麻烦,因为很难说从哪里开始。
如何为以下示例 UI 创建最小的测试设置(仅包含两个类)?
约束:Java SE、Swing UI、Maven 项目、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;
}
}
我知道这个问题本身非常广泛,因此我自己提供了一个答案 - 展示这个特定的例子。