January 21, 2008

Swing Acceptance Testing with JFC

After many years developing for the Web I found myself having to do some Swing code and *obviously* had to do some testing for it. I went with JFC for the functional tests and here’s a little cookbook.

The test class extends from JFCTestCase
public class CurCalcTest extends JFCTestCase
The main JFC class to take heed is JFCTestHelper. Probably a Good Idea is to set it in the setup method:

protected void setUp() throws Exception {
setHelper(new JFCTestHelper());

After that, my approach was to get the container under test/investigation:

JPanel curCalcPanel = (JPanel) frame.getContentPane().getComponent(0);

And then obtain each one of the elements I want to manipulate, such as comboBoxes, textFields, and etc.:

NamedComponentFinder amountFinder = new NamedComponentFinder(
JTextField.class, "jTextFieldAmount");
amountField = (JTextField) amountFinder.find(curCalcPanel, 0);

NamedComponentFinder countryComboFinder = new
NamedComponentFinder(JComboBox.class, "jComboBoxCountry1");
countryCombo = (JComboBox) countryComboFinder.find(curCalcPanel, 0);

NamedComponentFinder messagesFinder = new

NamedComponentFinder(JLabel.class, "messages");
messagesLabel = (JLabel) messagesFinder.find(curCalcPanel, 0);

Now I can insert my keystrokes/clicks using the helper:

getHelper().sendString(new StringEventData(this, amountField, "1"));
getHelper().enterClickAndLeave(new JComboBoxMouseEventData(this,
countryCombo, 1, 1));

getHelper().enterClickAndLeave(new MouseEventData(this, convertButton));

And assert my expectation(s):

Assert.assertEquals("0.97478773", messagesLabel.getText());

JFC is another fantastic tool by ThoughtWorks. It is a very useful framework but not friendly all of the time. For instance, if you forget to identify the elements properly via the setName() method, and try to use NamedComponentFinder no error is given, the thread just sits in there without complaining about anything.

No comments:

Post a Comment