Reputation: 31
I have a problem while testing a JavaFX application with TestFx. I put a sample, using just a VBox instead of a BorderPane that i use in real application. I just fill the pane with a canvas, to not have it empty, but with or without nothing changes.
public class MainPanelTest extends ApplicationTest {
Pane toTest;
boolean pressed = false;
@Override
public void start(Stage stage) {
toTest= new VBox(new Canvas(800,800));
toTest.setOnKeyPressed(e -> {
System.out.println("Pressed");
pressed = true;
});
stage.setScene(new Scene(toTest));
stage.show();
stage.toFront();
}
@Test
public void test_keyPressed_D() {
clickOn(toTest);
press(KeyCode.D);
WaitForAsyncUtils.waitForFxEvents();
assertTrue(pressed);
}
}
If instead of a Pane, I use a TextField for instance, all is working:
public class MainPanelTest extends ApplicationTest {
TextField toTest;
boolean pressed = false;
@Override
public void start(Stage stage) {
toTest= new TextField();
toTest.setOnKeyPressed(e -> {
System.out.println("Pressed");
pressed = true;
});
stage.setScene(new Scene(toTest));
stage.show();
stage.toFront();
}
@Test
public void test_keyPressed_D() {
clickOn(toTest);
press(KeyCode.D);
WaitForAsyncUtils.waitForFxEvents();
assertTrue(pressed);
}
}
Is there something that I'm missing here? In real application, when i press a key the event is catched correctly.
Upvotes: 1
Views: 388
Reputation: 31
I figured out how to test it, it's needed to explicit request focus for the Pane.
Simply adding this line toTest.requestFocus();
.
This test pass:
public class MainPanelTest extends ApplicationTest {
Pane toTest;
boolean pressed = false;
@Override
public void start(Stage stage) {
toTest= new VBox(new Canvas(800,800));
toTest.setOnKeyPressed(e -> {
System.out.println("Pressed");
pressed = true;
});
stage.setScene(new Scene(toTest));
stage.show();
toTest.requestFocus();
}
@Test
public void test_keyPressed_D() {
press(KeyCode.D);
WaitForAsyncUtils.waitForFxEvents();
assertTrue(pressed);
}
}
Upvotes: 2