Reputation: 11
I want to test, if a certain TextField
(maybe there are several TextFields
) has an EventHandler
set via setOnAction
. In the test code I can set the content (e.g. "HelloWorld") into the TextField
. In my understanding I have to place the curser at the end of the text in the TextField and then, call press(KeyCode.ENTER)
. Is there a TestFX call to place the curser a a certain point within a certain TextField? Or is there another way to test this?
Regards, Jörg
[EDIT] Here is an example:
package testestfx;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.layout.VBox;
public class SimpleGui extends VBox {
private static final org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(SimpleGui.class);
private TextField field1;
private TextField field2;
private Label label;
public SimpleGui() {
field1 = new TextField("Textfield1");
field2 = new TextField("Textfield2");
field1.setOnAction((event) -> onActionDoThis());
field2.setOnAction((event) -> onActionDoThat());
label = new Label("Label");
getChildren().addAll(field1, field2 );
}
public TextField getField1() {
return field1;
}
public TextField getField2() {
return field2;
}
public Label getLabel() {
return label;
}
void onActionDoThis() {
logger.info("This");
label.setText("This");
}
void onActionDoThat() {
logger.info("That");
label.setText("That");
}
}
And here is the test:
package testtestfx;
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.control.TextField;
import javafx.scene.input.KeyCode;
import javafx.stage.Stage;
import org.junit.Test;
import org.testfx.framework.junit.ApplicationTest;
import testestfx.SimpleGui;
import static org.junit.Assert.assertEquals;
public class TestSimpleGUI extends ApplicationTest {
private static final org.slf4j.Logger logger =
org.slf4j.LoggerFactory.getLogger(TestSimpleGUI.class);
private SimpleGui gui;
@Override
public void start(final Stage stage) throws Exception {
super.start(stage);
gui = new SimpleGui();
stage.setScene(new Scene(gui));
stage.show();
}
@Test
public void testEnterKeystroke() {
TextField t2 = gui.getField2();
TextField t1 = gui.getField1();
Label l1 = gui.getLabel();
t2.setText("bar");
t1.setText("foo");
press(KeyCode.ENTER);
assertEquals("That", l1.getText());
}
}
The console output is:
15:43:29.366 [JavaFX Application Thread] [INFO] SimpleGui - This
org.junit.ComparisonFailure:
Expected :That
Actual :This
```
Upvotes: 1
Views: 519
Reputation: 45
You can set the focus on a TextField like this:
myTextField.requestFocus();
kind regards
Amadeus
Upvotes: 1