If the test tries to access a property from the returned widget, there will be an exception thrown. For example, ctabs.get(0).getText()
will result in an Invalid thread access SWT error.
To perform testing on widgets, the code has to run in the UI thread. Either the Display.getDefault().syncExec()
or the equivalent Synchronizer
class can be used, but SWTBot has a UIThreadRunnable
that can launch code and a general interface called StringResult
, which is like a Runnable
that can return a String
value through syncExec
.
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 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
method call means that the result is guaranteed to be available for testing. If an asyncExec
method call is used, then 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 effectively wraps this up in the UIThreadRunnable
, in which an ArrayList
is created to hold the single element.
Java 8 makes this significantly easier in that it allows lambda methods to be executed. For example, the execution can be replaced with the much shorter version as a lambda:
String tabText = UIThreadRunnable.syncExec(() -> ctabs.get(0).getText());
13.59.18.83