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

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) {
        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 {

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



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.

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.

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




Need Your Help

MDX Query fails in Petaho BA server

mdx pentaho olap mondrian

My database connection is MySQL through JDBC, standard innodb.