Skip to content

Test Swing UI using JUnit5

Roman Wolf edited this page Jul 14, 2025 · 4 revisions

Design

With JUnit5 the design approach changes. The allow Windowtester to check your Swing UI the following information must be provided:

  • The object that represent the UI under test -- Windowtester will take to display this UI reducing your code

Windowtester will provide you access to the UIContext, which allows you:

  • To apply checks on your UI
  • To interact with your UI

Write a Unit test class

The following example illustrates the basic unit test class design:

@ExtendWith(WindowtesterExtension.class)
class DialogTest {

  @UIUnderTest
  private JDialog dialog = new SimpleDialog();

  @Test
  void testMain(@SwingUIContext IUIContext ui) throws Exception {
    ui.wait(new WindowShowingCondition("Simple Dialog"), 1_000);

    ui.click(new JButtonLocator("A question button."));
    ui.wait(new WindowShowingCondition("Question"), 1_000);

    ui.click(new JButtonLocator("Yes"));
  }
}
``
`

1. @ExtendsWith(WindowtesterExtension.class)

Set the overall extension so Windowtester can provide you maximum support on your test class.
The extension will support 2 annotations:

- @UIUnderTest
- @SwingUIContext

2. @UIUnderTest

This annotation marks the UI under test, the UI object that represents the visible object to run your tests on.
This annotation is optional.
If used, instantiate the object and Windowtester will take care to make your UI visible.
If not used you have to render your UI by yourself, e.g. in the @BeforeEach method.

This object is normally:

- A window
- A frame
- A dialog
- A panel

But it can be basically any Swing UI class which can be drawn right away.

3. @SwingUIContext

This context can be injected as method parameter on every @Test method.
It provides you the access to operate on the UI (e.g. move the mouse, enter keyboard strokes) as well as run condition check on your current UI.

Clone this wiki locally