How to activate JButton ActionListener inside code (in test units)?

I need to activate the JLutton ActionListener in the JDialog so that I can run some unit tests 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 a 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());
    }
}

      

It might seem like overkill to do in a unit test, but the actual class is much more complex than that ...

0


source to share


3 answers


AbstractButton.doClick



Your tests can run faster if you use a form that takes an argument and gives it a shorter delay. Call blocks for delay.

+5


source


If you have non-trivial code directly in your event handler that requires unit testing, you may need to adopt the MVC pattern and move the code to the controller. Then you can unit test the code using the mock View and you don't need to programmatically click the button at all.



+2


source


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

      

+1


source







All Articles