Monthly Archives: January 2014

Testing a plain SWT Application with SWTBot

Revision History
18 April 2014 Modified the SWTBot test so that it can be reused also in a test suite (see the comments to this post).

I happened to give a lecture at the University of Florence on Test Driven Development; besides the standard Junit tests I wanted to show the students also some functional tests with SWTBot. However, I did not want to introduce Eclipse views or dialogs, I just wanted to test a plain SWT application with SWTBot.

In the beginning, it took me some time to understand how to do that (I had always used SWTBot in the context of an Eclipse application); thanks to Mickael Istria, who assisted me via Skype, it ended up being rather easy.

You can find this example here: https://github.com/LorenzoBettini/junit-swtbot-example.

The SWT application is a simple dialog that computes the factorial of the given input (nothing fancy, its code can be seen here).

swtbot-test-example1

If we now want to test this SWT application with SWTBot, we can write an abstract base class that we use for our tests (see also the online code)

And we use this base class in our tests, for instance

There are a few things to note in the abstract base class:

  • You need to spawn the application in a new thread (the bot will run in a different thread)
  • You must start the application before creating the bot (otherwise the Display will be null)
  • after that you can simply use SWTBot API as you’re used to.

Note that the thread will create our window and then it will enter the event loop; this thread synchronizes with the @Before method (executed before each test), which creates the SWTBot (using the shell created by the thread). The @After method (executed after each test), will close our window, so that each test is independent from each other. The thread executes in an infinite loop, thus as soon as the shell is closed it will create a new one, etc.

Of course, this must be executed as a “Junit test”, NOT as a “Plug-in Junit test”, neither as a “SWTBot Test”, since we do not want any Eclipse application while running the test:

swtbot-test-example2

In the sources of the example you can find also the files to run the tests headlessly with Buckminster or with Maven/Tycho. Just enter the directory mathutils.build and

for Buckminster or

for Maven.

For Buckminster, you just need to save the launch configuration you used to run the test, and use the junit command:

For Tycho, you must specify <packaging>eclipse-test-plugin</packaging>, but without further configuration. This will default useUIHarness to false.

During the headless run, first the Junit tests for the implementation of the factorial will be executed (these are not interesting in the context of SWTBot) and then the SWTBot tests will be executed.