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
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 to share