Note that if the test tries to access a property from the returned widget, there may be an invalid thread-access error. For example, ctabs.get(0).getText()
will result in an Invalid thread access
SWT error.
To perform tests on widgets, the code has to be run in the UI thread. Either the Display.getDefault().syncExec()
or the equivalent Synchronizer
class can be used, but SWTBot has a general interface called StringResult
, which is like a Runnable
method that can return a String
value through syncExec()
on the bot.
testTimeZone()
method of the UITest
class, create a new StringResult
and pass it to UIThreadRunnable.syncExec()
.run()
method, get the first cTabItem
and return its text value.Runnable
method has been run, assert that the value is Africa
.String tabText = UIThreadRunnable.syncExec(new StringResult() { @Override public String run() { return ctabs.get(0).getText(); } }); assertEquals("Africa", tabText);
To interact with widgets, code must be run on the UI thread. To run code on the UI thread in SWT, it needs to be wrapped into a Runnable
, which needs to be posted to the display (or Synchronizer
) and executed there.
Using a syncExec()
means that the result is guaranteed to be available for testing. If an asyncExec()
operation is used, the result may not be available by the time the following assert operation runs.
To pass a value back from the UI thread to a non-UI thread, the result has to be stored in a variable. This has to be either a field on the class or a value in a final array. The StringResult
of the SWTBot
package wraps this up effectively in the UIThreadRunnable
, in which an ArrayList
is created to hold the single element.
Java 8 will make this significantly easier in that it will allow for lambda methods to be executed. At the time of writing, the syntax of Java 8 was not finalized.