我有一个 JavaFX 程序,它连接到外部 Web API 以下载一些数据。我在单元测试中使用模拟来测试部分逻辑,但现在我想测试 GUI,即运行程序并查看下载的数据放入 TableView 或 ListView 中时的样子。
public class Main extends Application {
private MainController mainController;
@Override
public void start(Stage primaryStage) throws Exception {
FXMLLoader fxmlLoader = new FXMLLoader(getClass().getResource("/fxml/main.fxml"));
Parent root = fxmlLoader.load();
mainController = fxmlLoader.getController();
primaryStage.setTitle("Title");
primaryStage.setScene(new Scene(root, 600, 550));
primaryStage.show();
}
@Override
public void stop() {
mainController.close();
}
}
我试图做的是有一个测试方法,使用 Aplication.launch
启动应用程序,然后调用 MainController
的方法 setApi
用模型替换默认的 API 管理器对象。不幸的是我不知道如何访问 mainController
对象。所以,我的问题是——能做到吗?如果是的话 - 怎么办?如果不是 - 使用示例数据测试 GUI 的其他方法是什么?
最佳答案
我使用TestFX与 JBehave 结合进行用户界面测试。严格来说,后者对于您的案例来说并不是必需的,您可以使用普通的 JUnit 测试用例来完成同样的任务。
在 TestFX 中,您可以获得执行测试的舞台,并将场景传递给它以设置用户界面。
按照您的示例,您的测试将加载 FXML,将 root
传递给 TestFX,然后查询 MainController
。
当您拥有 Controller 后,您可以操纵它并使用 TestFX 模拟点击、按键并验证节点状态。
@When("the application is closed")
public void whenTheApplicationIsClosed() throws TimeoutException, InterruptedException {
clickOn("#filemenu");
clickOn("#menuitem-quit");
}
@Given("a workbench with no changed editors")
public void givenAWorkbenchWithNoChangedEditors() throws TimeoutException, InterruptedException {
for (int i = 1; i <= 5; i++) {
TestEditor editor = new TestEditor(i);
FxToolkit.setupFixture(() -> workbench.getParts().add(editor));
}
}
@Given("a workbench with a single changed editor")
public void givenSingleChanged() throws TimeoutException {
TestEditor testEditor = new TestEditor(1);
FxToolkit.setupFixture(() -> workbench.getParts().add(testEditor));
List<Part> parts = workbench.getParts();
for (int i = 2; i < 5; i++) {
final Editor editor = new TestEditor(i);
FxToolkit.setupFixture(() -> parts.add(editor));
}
FxToolkit.setupFixture(testEditor::change);
}
@Then("a save content dialog is shown")
public void thenASaveContentDialogIsShown() throws InterruptedException {
verifyThat(Messages.getString("app.exit.unsavedchanges.header"), NodeMatchers.isVisible());
clickOn(Messages.getString("app.exit.unsavedchanges.quit"));
}
关于java - 提供示例数据来测试 JavaFX GUI,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43989304/