java - 如何对 ActionListener 进行 jUnit 测试
问题描述
我的班级有我想在其上运行 JUnit 测试的 actionPerformed 方法:
@Override
public void actionPerformed(ActionEvent actionEvent) {
try {
if (actionEvent.getSource() == returnButton && previousWindow.equals("menu")) {
MenuWindow menuWindow = new MenuWindow();
menuWindow.setMenuWindow();
}
if (actionEvent.getSource() == returnButton && previousWindow.equals("download")) {
DownloadWindow downloadWindow = new DownloadWindow();
downloadWindow.setDownloadWindow();
}
if (actionEvent.getSource() == returnButton && previousWindow.equals("upload")) {
UploadWindow uploadWindow = new UploadWindow();
uploadWindow.setUploadWindow();
}
} catch (Exception e) {
LOGGER.info(e.toString());
}
}
我听说过一些关于调用 actionListener 的 doClick 方法,但 JButton 是一个局部变量,所以我不知道如何调用它:
/**
* This method sets the variables of the frame to be put in the help window
* @return
*/
public JFrame setHelpWindow() {
JFrame helpFrame = new JFrame();
helpFrame.setDefaultCloseOperation(EXIT_ON_CLOSE);
helpFrame.setLayout(new GridBagLayout());
helpFrame.setTitle("Help");
helpFrame.setSize(700, 300);
helpFrame.setLocationRelativeTo(null);
helpFrame.setDefaultCloseOperation(WindowConstants.EXIT_ON_CLOSE);
helpPanel = setHelpPanel();
helpFrame.add(helpPanel, frameGbc);
helpFrame.getContentPane().setLayout(new GridBagLayout());
helpFrame.setVisible(true);
return helpFrame;
}
/**
* This method sets the variables of the panel to be put in the frame
* @return
*/
private JPanel setHelpPanel() {
panelGbc.fill = GridBagConstraints.HORIZONTAL;
panelGbc.insets.bottom = 1;
panelGbc.insets.top = 1;
panelGbc.insets.right = 1;
panelGbc.insets.left = 1;
panelGbc.weightx = 1;
panelGbc.weighty = 1;
helpPanel.setLayout(new GridBagLayout());
setText(helpPanel);
setButtons(helpPanel);
setAction();
helpPanel.setSize(700, 300);
return helpPanel;
}
/**
* This method sets the variables of the buttons
* @param helpPanel
*/
private void setButtons(JPanel helpPanel) {
returnButton = new JButton("Return");
panelGbc.gridx = 0;
panelGbc.gridy = 2;
panelGbc.gridwidth = 1;
panelGbc.gridheight = 1;
helpPanel.add(returnButton, panelGbc);
}
如果有人能告诉我如何测试 JButton 并获得 actionListener 的报道,我将不胜感激。谢谢你。
解决方案
最后我使用了 doClick 并测试了没有抛出异常:
@Test
@DisplayName("ActionListener test")
void testActionListener(){
HelpWindow helpWindow = new HelpWindow("menu");
helpWindow.setHelpWindow();
assertDoesNotThrow(() -> helpWindow.getReturnButton().doClick());
}
我为 JButton 创建了一个 getter,使用 doClick 激活并使用 assertDoesNotThrow 进行了测试。给了我 100% 的覆盖率并测试了所有的线路(与按下按钮有关)。
推荐阅读
- json - Moshi 相当于 Gson 的“serializeNulls”
- python - Unite 测试中的错误。Python 模板发布-订阅
- php - 如何将 PHP DB 数据转换为具有不同列标题的 JSON
- php - 帮助初学者找到他没有制作的网络主要源代码
- javascript - use concat instead of es6 spread in adding array of object in react
- c# - 使用 CheckBox 更快地取消选中/检查 500 多个 DataGridViewRows
- c++ - 为什么我不能编译 Boost.Serialization 演示?
- r - R通过部分匹配合并2个表/数据框
- kotlin - 如何在kotlin中声明一个可为空的函数参数
- python - groupby 获取平均值,使用动态条件