Robin Jonsson
Robin Jonsson

Reputation: 2851

TestFX 4 Selecting a value from ChoiceBox / Menu

I'm scratching my head here trying to get my TestFX robot to click on a Menu and then a MenuItem.

None of the above classes derive from Node so I cannot use fxRobot.clickOn(Node node).

Does anyone else have an idea of how to accomplish this? Besides simply using a TextMatcher, which searches through the whole scope.

Example of MenuBar with a menu:

<MenuBar fx:id="mainMenuBar">
        <menus>
            <Menu mnemonicParsing="false" style="-fx-font-weight: bold;" text="MainMenu">
                <items>
                    <MenuItem mnemonicParsing="false" style="-fx-font-weight: normal;" text="About" />
                    <MenuItem mnemonicParsing="false" style="-fx-font-weight: normal;" text="Exit" />
                </items>
            </Menu>

How would I achieve a robot clicking on the top Menu (preferrably by the visible text of the menu) and the the menuItem inside (also preferrably selected by the visual text)

Example of ChoiceBox:

<ChoiceBox fx:id="myChoices" />

It's items are dynamically populated from my controller:

@FXML private ChoiceBox myChoices;

@FXML
public void initialize() {
    List<String> items = ItemsRepo.getItems();
    myChoices.setItems(FXCollections.observableArrayList(items))
}

I could first click the choiceBox via it's fx:id. But how would I then select one of it's items? Preferably from the items visible text. The items texts could interfer with other texts inside the application. So I want to make sure I click one of the choicebox items, not some other text.

Regards

Upvotes: 2

Views: 2642

Answers (2)

Balint Korcsmar
Balint Korcsmar

Reputation: 41

I had to fill a PopUp form in my test case which had some ChoiceBox input fields. The items of the ChoiceBox were visible on the Scene below the PopUp so find the item by its text was not possible (the robot usually clicked on another occurrence of the text). I achieved this with the FxRobotInterface as below.

clickOn("#choiceBox");
type(KeyCode.DOWN);
type(KeyCode.ENTER);

Like this the first item of the ChoiceBox was selected. You cannot perfectly control which item you select with this solution as the items might change, but it worked for my case.

Upvotes: 4

Fiona Buchanan
Fiona Buchanan

Reputation: 11

If you have the scene you can use lookup on the MenuBar, which is a Node within the scene.

MenuBar menuBar = scene.lookup("#menuBar");

You need the "#" in front of the identifier. Once you have the MenuBar you can iterate through the menus and the menu items in each menu.

Upvotes: 1

Related Questions