Java 如何使用Cancel和Ok按钮对JDialog进行单元测试
我试图做一个jUnit测试,测试jDialog的弹出窗口以及与jDialog关联的按钮。我认为我已经理解并编写了代码来确保jDialog不为null,但我不确定如何测试按钮。我想我不会有jUnit测试来允许对话框弹出,我必须单击其中一个按钮。我假设测试需要运行并执行所有操作,而无需单击任何内容。我使用过doClick(),但每次尝试使用断言时,代码中都会出现错误。我将如何测试按钮 jDialog类是:Java 如何使用Cancel和Ok按钮对JDialog进行单元测试,java,junit,jbutton,jdialog,Java,Junit,Jbutton,Jdialog,我试图做一个jUnit测试,测试jDialog的弹出窗口以及与jDialog关联的按钮。我认为我已经理解并编写了代码来确保jDialog不为null,但我不确定如何测试按钮。我想我不会有jUnit测试来允许对话框弹出,我必须单击其中一个按钮。我假设测试需要运行并执行所有操作,而无需单击任何内容。我使用过doClick(),但每次尝试使用断言时,代码中都会出现错误。我将如何测试按钮 jDialog类是: public class ExitDialog { JDialog exit
public class ExitDialog {
JDialog exitDialog = new JDialog();
JLabel textDisplay = new JLabel("<html> You are about to exit the Application! <br> Are you sure you want to proceed? <html>");
public JButton cancelButton = new JButton("Cancel");
JButton acceptButton = new JButton("Yes");
public void exitDialog(){
//sets up the dialog
exitDialog.setLayout(new FlowLayout());
exitDialog.setVisible(true);
exitDialog.setLocationRelativeTo(null);
exitDialog.setSize(270,110);
exitDialog.setTitle("Exit Confirmation");
//adds the text and button to the dialog
exitDialog.add(textDisplay);
exitDialog.add(cancelButton);
exitDialog.add(acceptButton);
//closes the dialog pop-up
cancelButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
exitDialog.dispose();
}
});
//Closes the application and then saves the current state
acceptButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
//need to make a save call here so if they do accept to close the application then auto saves the current edits
System.exit(0);
}
});
}
}
可能是这样的,正如Oracle所说:这个类用于生成本机系统输入事件,用于测试自动化、自运行演示以及其他需要控制鼠标和键盘的应用程序。Robot的主要目的是促进Java平台实现的自动化测试。因为您要求进行单元测试,所以我必须回答,这不是您想要创建的单元测试,而是集成/gui测试。通过单元测试,您可以测试一个单元的功能,该单元通常是一个方法,但您只有构造函数,没有其他功能(以及两个您无法访问的匿名ActionListener)。
public class ExitDialogTest {
private GUI.ExitDialog guiExitDialog;
/**
* @throws java.lang.Exception
*/
@Before
public void setUp() throws Exception {
guiExitDialog = new GUI.ExitDialog();
}
/**
* @throws java.lang.Exception
*/
@After
public void tearDown() throws Exception {
guiExitDialog = null;
}
/**
* Test method for {@link GUI.ExitDialog#exitDialog()}.
*/
@Test
public final void testExitDialog() {
assertNotNull(guiExitDialog);
}
/**
*
*/
@Test
public final void testExitDialogCancel() {
}
}