首页 > 解决方案 > 如何对 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 的报道,我将不胜感激。谢谢你。

标签: javaswingjunitjbuttonactionlistener

解决方案


最后我使用了 doClick 并测试了没有抛出异常:

@Test
@DisplayName("ActionListener test")
void testActionListener(){
    HelpWindow helpWindow = new HelpWindow("menu");
    helpWindow.setHelpWindow();

    assertDoesNotThrow(() -> helpWindow.getReturnButton().doClick());
}

我为 JButton 创建了一个 getter,使用 doClick 激活并使用 assertDoesNotThrow 进行了测试。给了我 100% 的覆盖率并测试了所有的线路(与按下按钮有关)。


推荐阅读