验证组合框的文本



我正在使用 https://github.com/TestFX/TestFX 进行javafx客户端的GUI测试。使用 testfx 查询,我得到了组合框,但我无法获取其文本进行验证。组合框显示枚举值,其文本由转换器和给定资源包解析。组合框的场景图如下所示:

javafx.scene.control.ComboBox
    javafx.scene.layout.StackPane:arrow-button
        javafx.scene.layout.Region:arrow
    com.sun.javafx.scene.control.skin.ComboBoxListViewSkin$4$1:null
        com.sun.javafx.scene.control.skin.LabeledText:null

comboBox.getValue()只给了我枚举值,但没有给我文本(我可以验证枚举值,但由于它是一个 gui 测试,所以应该验证显示的文本)。通过尝试,我发现comboBox.getChildrenUnmodifiable().toString()打印

[StackPane[id=arrow-button, styleClass=arrow-button], ComboBoxListViewSkin$5[id=list-view, styleClass=list-view], ComboBoxListViewSkin$4$1@4f65f1d7[styleClass=cell indexed-cell list-cell]'StringOfInterest']

末尾的字符串"StringOfInterest"正是我所需要的,但目前尚不清楚它来自哪里。通过查看javafx的源代码,似乎正在使用Node#toString。然而,目前还不清楚最后一部分("StringOfInterest")来自哪里。我试图获取组合框的所有子项的文本,但有问题的字符串不是其中的一部分。

如何提取字符串?

我找到了一种使用 TestFX 4 和 JavaFX 12 在组合框中获取文本的方法。不确定以下内容是否也适用于其他版本。诚然,它感觉有点笨拙和脆弱,但它给了我想要的结果。

ComboBox<String> comboBox = robot.lookup("#comboBox").queryComboBox();
ListCell<String> listCell = robot
    .from(comboBox)
    .lookup((Node node) -> node.getStyleClass().contains("list-cell") 
        && node.getParent() instanceof ComboBox)
    .<ListCell<String>>query();

我首先尝试只lookup(".list-cell"),但这实际上给了我两个结果,一个是 null 作为文本,另一个是所需的文本。带有 null 的那个嵌套在场景图中的某个位置,但我们感兴趣的那个将组合框作为父级。这就是查找检查的内容。

您现在可以验证组合框的文本:

assertThat(listCell.getText()).isEqualTo("expected text");

最新更新