![](/img/trans.png)
[英]How can I write a simple JUnit test to test a REST Controller
[英]How can I write a JUnit test on a button that makes a modal JDialog?
我目前正在使用Java swing应用程序,该应用程序从用户那里获得了多个输入。 有一次,我有一个JButton
,它的动作侦听器会生成一个模态JDialog
框架,用户可以在其中输入数据。 然后,该按钮获取数据并对其进行处理。 问题是我需要测试JButton
以确保其正常运行,但是由于它是模态的,因此在生成新Frame时,单元测试将立即停止。 如何测试按钮是否确实催生了新窗口,以及按钮的其余功能是否正常工作?
注意:
frame.setModal(false);
因为它包含在actionlistner中。 示例代码:
public void actionPerformed(ActionEvent e) {
InputDialog inputDialog = new InputDialog(button);
String value = inputDialog.open();
// I then do a bunch of stuff with value
}
--
public class InputDialog extends JDialog {
private JTextField field;
public String getInput() {
this.setVisible(true);
String result = field.getText();
return result;
}
public InputDialog(Component c){
// set the window settings
this.setUndecorated(true); // Remove title bar
this.setLayout(null);
this.setModal(true); // stops interactions with other windows
this.setLocationRelativeTo(c);
this.setSize(200, 125);
// make panel
JPanel panel = new JPanel();
panel.setBounds(0, 0, 200, 125);
panel.setLayout(null);
panel.setBackground(new Color(197, 211, 234));
panel.setBorder(BorderFactory.createEtchedBorder(EtchedBorder.RAISED));
// set up field
field = new JTextField();
field.setBounds(25, 25, 150, 25);
panel.add(field);
// set up enter button
JButton button = new JButton("Submit Value");
button.setBounds(25, 75, 150, 25);
button.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
me.dispose();
}
});
panel.add(button);
this.add(panel);
}
}
我认为您根本不想让单元测试打开任何UI框架/对话框。 尝试使用PowerMock之类的模拟库和模拟InputDialog
构造函数返回模拟InputDialog
并增加以编程方式单击JButton
时会调用InputDialog.opne()
方法的期望。
当然,测试产品的各个方面非常重要。 但是您的方法已经存在缺陷。
首先:您应该非常小心将什么代码放入ActionListener中。 含义:这些方法在事件分配器线程上调用。 当您在该线程上执行“太多”操作时,您会减慢甚至冻结整个UI。
然后:您必须将UI代码与业务逻辑完全隔离。 关于计算值的所有内容都应归入不同的类中,然后单独进行测试。
换句话说:您的ActionListener不会“用value
做事”-根本来说,侦听器知道如何使用其他类来“做那些事”。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.