Clean SWT Listener Notifcations with SWTEventHelper

Writing tests for SWT based UIs often requires to notify widget listeners programmatically. Unfortunately the code to create, initialize and finally to trigger the event is a bit verbose and distracts from the actual purpose of the test. After writing similar initialization routines a couple of times I came up with a little utility class that avoid these redundancies and make the code somewhat more expressive1

The class is called SWTEventHelper and uses a fluent interface coding style combined with static imports2 as known for example from Mockito. The following snippets demonstrate the usage by a simple example:
 
 

public class MouseDownCounter extends MouseAdapter {

  private int count;

  public MouseDownCounter( Control control ) {
    control.addMouseListener( this );
  }

  @Override
  public void mouseDown( MouseEvent event ) {
    count++;
  }

  public int getCount() {
    return count;
  }
}

Looking at the code of the MouseDownCounter one may consider it necessary to ensure that a mouse down event actually increases the count by one. With the SWTEventHelper a test to do so could look like this:

public class MouseDownCounterTest {

  @Rule
  public final DisplayHelper displayHelper = new DisplayHelper();

  @Test
  public void testMouseDownIncreasesCount() {
    Composite parent = displayHelper.createShell();
    Control control = new Label( parent, SWT.NONE );
    MouseDownCounter counter = new MouseDownCounter( control );

    trigger( SWT.MouseDown ).on( control );

    assertEquals( 1, counter.getCount() );
  }

  [...]
}

The test creates a ‘real’ SWT control3 in the build4 section of the test. After that the control is ‘wrapped’ by our unit under test, the MouseDownCounter. The following operate section creates a SWT.MouseDown Event using SWTEventHelper#trigger(int) and the listener that got registered at the Label control is notified via SWTEventHelper#on(Widget). Last but not least the check section ensures that the mouse down has actually increased the counter.

The SWTEventHelper furthermore provides a configuration method for each attribute of org.eclipse.swt.widgets.Event. Look at the following line of code to see how to fire an event notification with e.g. a certain Event#keyCode:

trigger( SWT.MouseDown ).withKeyCode( SWT.BUTTON1 ).on( control );

As I have used this little helper for over a hundred times now it might be useful for others too. Hence I set up a GitHub gist where you can download the SWTEventHelper code: https://gist.github.com/fappel/9426554

Don’t be shy, give it a try!

  1. Expressiveness is of course, at least to some extend, in the eye of the beholder
  2. Eclipse offers the possibility to configure content assist with static imports via the favorites preference settings which makes this approach even more comfortable
  3. The DisplayHelper reduces typing effort by handling Display related initialization and disposal automatically. You can find a description and a download link in the post A JUnit Rule to Ease SWT Test Setup
  4. The test formatting is based on the BUILD-OPERATE-CHECK pattern (Robert C. Martin, Clean Code, Chapter 9, Clean Tests). However in a real world scenario I would probably extract the build section into a separate method

 

Related Whitepaper:

Bulletproof Java Code: A Practical Strategy for Developing Functional, Reliable, and Secure Java Code

Use Java? If you do, you know that Java software can be used to drive application logic of Web services or Web applications. Perhaps you use it for desktop applications? Or, embedded devices? Whatever your use of Java code, functional errors are the enemy!

To combat this enemy, your team might already perform functional testing. Even so, you're taking significant risks if you have not yet implemented a comprehensive team-wide quality management strategy. Such a strategy alleviates reliability, security, and performance problems to ensure that your code is free of functionality errors.Read this article to learn about this simple four-step strategy that is proven to make Java code more reliable, more secure, and easier to maintain.

Get it Now!  

Leave a Reply


2 + = nine



Java Code Geeks and all content copyright © 2010-2014, Exelixis Media Ltd | Terms of Use | Privacy Policy
All trademarks and registered trademarks appearing on Java Code Geeks are the property of their respective owners.
Java is a trademark or registered trademark of Oracle Corporation in the United States and other countries.
Java Code Geeks is not connected to Oracle Corporation and is not sponsored by Oracle Corporation.

Sign up for our Newsletter

20,709 insiders are already enjoying weekly updates and complimentary whitepapers! Join them now to gain exclusive access to the latest news in the Java world, as well as insights about Android, Scala, Groovy and other related technologies.

As an extra bonus, by joining you will get our brand new e-books, published by Java Code Geeks and their JCG partners for your reading pleasure! Enter your info and stay on top of things,

  • Fresh trends
  • Cases and examples
  • Research and insights
  • Two complimentary e-books