views:

1095

answers:

3

Hi, 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...

+3  A: 

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.

Tom Hawtin - tackline
Thanks, I can never find the methods that I need...
Hoffmann
It's not an obvious method.
Tom Hawtin - tackline
+2  A: 

If you have non-trivial code directly in your event handler that needs unit testing, you might want to consider adopting the MVC pattern and 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.

Dan Vinton
The problem is that I'm extending a class (not actually JDialog) that I did not made, the maker of that class didn't use the MVC pattern. Thanks for the info anyway.
Hoffmann
+1  A: 

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