I was trying to use TestFX to test my application. I would like to run the test for the method of my controller.
Main.java:
public class Main extends Application {
try{
new Flow(ManageCtrl.class).startInStage(primaryStage);
} catch (Exception ex) {
LOGGER.log(Level.SEVERE, null, ex);
}
}
ManageCtrl.java:
@ViewController("/FPManage.fxml")
public class ManageCtrl extends AnchorPane {
@FXML // fx:id="email"
private TextField email; // Value injected by FXMLLoader
public void setEmail(String address) {
this.email.setText(address);
}
}
ManageCtrlTest.java:
public class ManageCtrlTest extends ApplicationTest {
@Override
public void start(Stage stage) {
try {
new Flow(ManageCtrl.class).startInStage(stage);
} catch (FlowException ex) {
Logger.getLogger(ManageCtrlTest.class.getName()).log(Level.SEVERE, null, ex);
}
}
@Test
public void testSetEmail() {
ManageCtrl instance = new ManageCtrl();
instance.setEmail("test@gmai.com");
assertEquals("test@gmail.com", ((TextField)GuiTest.find("#email")).getText());
}
}
But I get the following Exception:
testSetEmail Failed: java.lang.illegalStateException: Not on FX application thread; currentThread = Test worker
java.lang.illegalStateException: Not on FX application thread; currentThread = Test Worker
Thanks for the help.
The
IllegalStateException
is related to the nature of JavaFX and TestFX.ManageCtrl
extends fromAnchorPane
which is one of JavaFX'sScene
objects that all need to be constructed within the JavaFX thread (also known as JavaFX application thread or JavaFX user thread). You can useApplicationTest#interact
to constructManageCtrl
within the JavaFX thread:However this will throw a
NullPointerException
which is caused by the nature of DataFX which is used withnew Flow(ManageCtrl.class)
.new Flow(ManageCtrl.class).startInStage(stage)
will inject all@FXML
-annotated fields in the controller with objects defined in your@ViewController
—new ManageCtrl()
won't. We can solve this problem by constructingManageCtrl
into the fieldcontroller
before the test:You can now test your controller with:
The whole thing is detailed in an issue on GitHub. I've also created a pull request on Bitbucket that tries to simplify testing on this regard.