A JUnit Rule to Ease SWT Test Setup
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.
Testing with JUnit
Testing with JUnit is one of the most valuable skills a Java developer can learn. No matter what your specific background, whether you’re simply interested in building up a safety net to reduce regressions of your desktop application or in improving your server-side reliability based on robust and reusable components, unit testing is the way to go.
Frank has written a book that gives a profound entry point in the essentials of testing with JUnit and prepares you for test-related daily work challenges.
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:
It is available for download in my JUnit 4 templates gist: https://gist.github.com/fappel/8863732
Hope you like it ;-)
- Xmas Clean Sheet Update (0.9) - 21. December 2021
- Clean Sheet Service Update (0.8) - 23. May 2020
- Clean Sheet Service Update (0.7) - 24. April 2020