Product Development in Brisbane

Adding a swing component to a Form Test Driven

Three steps to getting a component displayed (assuming that there is a subclass of JPanel being used):

1) add a reference to the component to the subComponent
assertNotNull(container.subComponent);

2) Check that the component has the right stuff
assertEquals(”expected text”, container.subCompoent.getText());
etc…

3) Check that the component is going to be visible on the screen
assertEquals(container, container.subComponent.getParent()).

In practice for me I have added another panel to the containment hierarchy in order to use a JGoodies builder to do the laying out. This means that I have made the assert:
assertEquals(container.jgoodiesPanel, container.subComponent.getParent()).

I have also got an assertion that looks like this:
assertEquals(container, container.jgoodiesPanel.getParent()).

This ensures my JGoodies panel is made visible.

After doing this I can do the visual check to make sure it performs as expected. Which it does :).

2 Responses to “Adding a swing component to a Form Test Driven”

  1. ana theeson Says:

    Sorry, but thats the worst misuse of unit testing I have ever seen. When testing a UI you need to test the function of the form, not the construction.

    This is like having a class with a private field that you set to 6 through a constructor. You do not need to do assertEquals(myfield, 6), this is un-necessary testing.

    How long does it take to just view the form (JDemo or others) compared to creating your unit test for it? In my opinion its a complete waste of time testing that you add something AFTER you add it…?

    There are a time and place for unit tests. Usually the best place to test forms is by simulating user input (java.awt.Robot) then testing to see if the MODEL behind the form is responding correctly.

  2. Rob Says:

    To each their own. I am very happy with the approach.

    Perhaps I didn’t make it clear that each of those steps is preformed before the components are added to the form. It is the application of approaches described in books like Kent Beck’s Test Driven Development.

    I agree that having the tests to support the view/model interaction is important as well, and will be doing that. The idea of being able to have a series of tests that checks that the components are on the screen is important, because this is a seperate concern to the hooking up of the components to the model.

    That is the motivation for the tests.

Leave a Reply