使用Swing开发Java桌面应用程序时,我遇到了直接测试UI的需求,而不仅仅是通过单元测试来测试底层控制器/模型类。如何开始:使用AssertJ Swing测试Java Swing GUI
这个answer (on "What is the best testing tool for Swing-based applications?")建议使用FEST,这是不幸中止。 但是,还有一些项目从FEST离开的地方继续。其中一个(在answer中提到)引起了我的注意,正如我之前在单元测试中使用的那样:AssertJ。
显然有AssertJ Swing,这是基于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;
}
}
我知道,这个问题本身是非常广泛的,因此,我提供一个答案我自己 - 显示这个特殊的例子。
此问题解答是为了回应这个答案的评论中的请求而创建的:https://stackoverflow.com/a/80222/5127499 – Carsten