Java 如何进行jUnit测试和ActionListener
我的类具有actionPerformed方法,我希望对该方法运行JUnit测试:Java 如何进行jUnit测试和ActionListener,java,swing,junit,jbutton,actionlistener,Java,Swing,Junit,Jbutton,Actionlistener,我的类具有actionPerformed方法,我希望对该方法运行JUnit测试: @Override public void actionPerformed(ActionEvent actionEvent) { try { if (actionEvent.getSource() == returnButton && previousWindow.equals("menu")) { MenuWindow menuW
@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%的覆盖率并测试了所有线路(与按下按钮有关)