A JUnit Rule to Ease SWT Test Setup

Home  >>  Eclipse  >>  A JUnit Rule to Ease SWT Test Setup

A JUnit Rule to Ease SWT Test Setup

On February 25, 2014, Posted by , In Eclipse,JUnit, By ,,,,, , With No Comments

Rüdiger and I have written a lot of SWT test cases for our current RCP project lately. Most of the time we can execute them as plain JUnit tests. Still they also have to run in a RCP integration environment. Long story short we wrote a DisplayHelper fixture to reduce redundancy and handle display related stuff for both cases properly. With stuff I mean disposal of open shells, flushing of pending events and a few other goodies.

If you are interested, the DisplayHelper is available as a GitHub gist. The download also contains a little demo that shows what the helper can do:

https://gist.github.com/fappel/9207164

As an interesting side note I’d like to mention that the helper wasn’t a rule right from the start. It was used like this (which is still possible for particular use cases):

public class FooTest {
  
  private DisplayHelper displayHelper;

  @Before
  public void setUp() {
    displayHelper = new DisplayHelper();
  }
  
  @After
  public void tearDown() {
    displayHelper.dispose();
  }
  
  @Test
  public void testFoo() {
    // now you can do the important stuff
  }
}

But then Holger‘s post about his simple Tabris/RAP Test Runner rang a bell. I did not strive for a test runner, but why not using an JUnit TestRule? Well, this should probably have been obvious for someone who has written a post called JUnit Rules… Anyway, it workes like a charm! Now the same test case can be written as:

public class FooTest {
  
  @Rule
  public DisplayHelper displayHelper = new DisplayHelper();
  
  @Test
  public void testFoo() {
    // now you can do the important stuff even faster...
  }
}

Less code, less typing, less chances to do something wrong – such things make me happy :-)

And to let you participate with my happiness I also created little Eclipse java template to generate JUnit 4 Rules:

rule-selection

It is available for download in my JUnit 4 templates gist: https://gist.github.com/fappel/8863732

Hope you like it ;-)

Follow me

Frank Appel

Frank is a stalwart of agile methods and test driven development in particular. He understands software development as a craftsmanship based on a well-balanced mix of knowledge and the experience of the daily work.

fappel@codeaffine.com
Follow me

Latest posts by Frank Appel (see all)

Leave a Reply

Your email address will not be published. Required fields are marked *

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>