java 如何在代码中激活 JButton ActionListener(单元测试目的)?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/329118/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-29 11:59:13  来源:igfitidea点击:

How do I activate JButton ActionListener inside code (unit testing purposes)?

javaunit-testingswingjunit

提问by Hoffmann

I need to activate a JButton ActionListener within a JDialog so I can do some unit testing using JUnit.

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

Basically I have this:

基本上我有这个:

    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;
    }

}

then I have my JUnit file:

然后我有我的 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());
    }
}

This may sound redundant to do in a unit test, but the actual class is a lot more complicated than that...

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

回答by Tom Hawtin - tackline

AbstractButton.doClick

AbstractButton.doClick

Your tests might run faster if you use the form that takes an argument and give it a shorter delay. The call blocks for the delay.

如果您使用带参数的形式并为其提供更短的延迟,则您的测试可能会运行得更快。调用阻塞延迟。

回答by Dan Vinton

If you have non-trivial code directly in your event handler that needs unit testing, you might want to consider adopting the MVC patternand moving the code to the controller. Then you can unit test the code using a mock View, and you never need to programmatically press the button at all.

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

回答by Markus Lausberg

You can use reflection to get the button at runtime and fire the event.

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

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();