TestFx入门

我在使用Oracle的JavaFx HelloWorld应用程序使用TestFx时遇到了一些麻烦:

public class HelloWorld extends Application { public static void main(String[] args) { launch(args); } @Override public void start(Stage primaryStage) { primaryStage.setTitle("Hello World!"); Button btn = new Button(); btn.setText("Say 'Hello World'"); btn.setOnAction(new EventHandler() { @Override public void handle(ActionEvent event) { System.out.println("Hello World!"); } }); StackPane root = new StackPane(); root.getChildren().add(btn); primaryStage.setScene(new Scene(root, 300, 250)); primaryStage.show(); } } 

TestFx junit测试:

 class MyTest extends GuiTest { public Parent getRootNode() { return nodeUnderTest; } 

nodeUnderTest应该为这个例子做些什么?

TestFx是一个unit testing框架,因此它旨在抓取部分GUI实现并对其进行测试。 这要求您首先提供这些部件,并通过使用ID标记它们来测试目标(按钮等)。

getRootNode()为GUI测试的以下测试过程提供了根。 在上面的示例中,StackPane根可能是候选者…但是这要求您将其用于测试以允许:

  class MyTest extends GuiTest { public Parent getRootNode() { HelloWorld app = new HelloWorld(); return app.getRoot(); // the root StackPane with button } } 

因此,必须修改应用程序以实现getRoot(),返回StackPane及其内容以进行测试,而不需要start()方法。

你可以运行测试……

 @Test public void testButtonClick(){ final Button button = find("#button"); // requires your button to be tagged with setId("button") click(button); // verify any state change expected on click. } 

还有一种简单的方法可以测试整个应用程序。 为了确保您的应用程序已正确初始化和启动,需要由JavaFX应用程序启动器启动。 不幸的是,TestFX不支持开箱即用(至少我没有找到任何方法)但你可以通过inheritanceGuiTest轻松完成:

 public class HelloWorldGuiTest extends GuiTest { private static final SettableFuture stageFuture = SettableFuture.create(); protected static class TestHelloWorld extends HelloWorld { public TestHelloWorld() { super(); } @Override public void start(Stage primaryStage) throws IOException { super.start(primaryStage); stageFuture.set(primaryStage); } } @Before @Override public void setupStage() throws Throwable { assumeTrue(!UserInputDetector.instance.hasDetectedUserInput()); FXTestUtils.launchApp(TestHelloWorld.class); // You can add start parameters here try { stage = targetWindow(stageFuture.get(25, TimeUnit.SECONDS)); FXTestUtils.bringToFront(stage); } catch (Exception e) { throw new RuntimeException("Unable to show stage", e); } } @Override protected Parent getRootNode() { return stage.getScene().getRoot(); } // Add your tests here }