【问题标题】:How do I activate JButton ActionListener inside code (unit testing purposes)?如何在代码中激活 JButton ActionListener(单元测试目的)?
【发布时间】:2008-11-30 17:54:01
【问题描述】:

我需要在 JDialog 中激活一个 JButton ActionListener,以便我可以使用 JUnit 进行一些单元测试。

基本上我有这个:

    public class MyDialog extends JDialog {
    public static int APPLY_OPTION= 1;
    protected int buttonpressed;
    protected JButton okButton;
    public MyDialog(Frame f) {
        super(f);
        okButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                buttonpressed= APPLY_OPTION;
            }
        } );
    public int getButtonPressed() {
        return buttonpressed;
    }

}

然后我有我的 JUnit 文件:

public class testMyDialog {

    @Test
    public void testGetButtonPressed() {
        MyDialog fc= new MyDialog(null);
        fc.okButton.???????? //how do I activate the ActionListener?
        assertEquals(MyDialog.APPLY_OPTION, fc.getButtonPressed());
    }
}

这在单元测试中听起来可能是多余的,但实际的类比这要复杂得多......

【问题讨论】:

    标签: java unit-testing swing junit


    【解决方案1】:

    AbstractButton.doClick

    如果您使用带有参数的表单并给它一个更短的延迟,您的测试可能会运行得更快。延迟调用阻塞。

    【讨论】:

      【解决方案2】:

      如果您的事件处理程序中直接有需要单元测试的重要代码,您可能需要考虑采用MVC pattern 并将代码移动到控制器。然后,您可以使用模拟视图对代码进行单元测试,而您根本不需要以编程方式按下按钮。

      【讨论】:

      • 问题是我正在扩展一个我没有创建的类(实际上不是 JDialog),该类的创建者没有使用 MVC 模式。无论如何感谢您的信息。
      【解决方案3】:

      您可以使用反射在运行时获取按钮并触发事件。

      JButton button = (JButton)PrivateAccessor.get(MyDialog , "okButton");
      Thread t = new Thread(new Runnable() {
          public void run() {
              // What ever you want
          };
      });
      
      t.start();
      
      button.doClick();
      
      t.join();
      

      【讨论】:

        【解决方案4】:

        我为 JButton 创建了一个 getter 并使用了 doClick。示例:

        @Test
        @DisplayName("ActionListener test")
        void testActionListener(){
            HelpWindow helpWindow = new HelpWindow("menu");
        
            assertDoesNotThrow(() -> helpWindow.getReturnButton().doClick());
        }
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 2016-08-25
          • 1970-01-01
          • 2022-07-09
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2012-09-10
          相关资源
          最近更新 更多