Java – How to activate JButton ActionListener inside code (unit testing purposes)

javajunitswingunit-testing

I need to activate a JButton ActionListener within a JDialog so I can do some unit testing using 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:

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…

Best Solution

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.

Related Question