如何使用testfx来测试javafx代码



我们计划在test-fx的帮助下测试我们的javafx场景生成器。为此,下载了testfx3.1.2 jar、hamcrest-core-1.3.jar、junit.jar、guava-18.0 jar文件。

请查看下面的代码,并给我一些如何启动gui的提示。我的控制器类也有一些额外的方法。

public class GuiMainController extends Application implements Initializable{
 @Override
    public void start(final Stage primaryStage) throws Exception {
        primaryStage.setTitle("Plugins");
        primaryStage.setResizable(false);
        primaryStage.setScene((Scene) FXMLLoader.load(getClass().getResource(
                "/../GuiMain.fxml")));
        primaryStage.show();
    }
    /**
     * to run this class locally.
     * @param args List of Command line arguments
     */
    public static void main(final String[] args) {
        launch(args);
    }
}

我的测试课在下面。

@Category(TestFX.class)
public class GuiMainTest extends GuiTest {
    @Override
    protected Parent getRootNode() {
        Parent parent = null;
        try {
            parent = (Parent)FXMLLoader.load(
               getClass().getResource("/../GuiMain.fxml"));
            return parent;
        } catch (IOException ex) {
                   }
        return parent;
    }
    @Test
    public void setBothnamesAndCheckEnabledSearchButton() {
        try{
        ComboBox<String> listPrj = find("#lstProject");//given combobox id.
        listPrj.setValue("ABC");
        if(listPrj.getValue().equals("ABC")) {
            System.out.println("success");
        }   
        }catch(NoNodesFoundException ne){
            System.out.println("node is not available" + ne.getMessage());
        }    }
}

它给了我一个例外:

java.lang.ClassCastException: javafx.scene.Scene cannot be cast to javafx.scene.Parent
    at com.trwautomotive.das.rhapsody.plugins.GuiMainTest.getRootNode(GuiMainTest.java:26)
    at org.loadui.testfx.GuiTest$1.run(GuiTest.java:130)
    at org.loadui.testfx.utils.FXTestUtils$4.call(FXTestUtils.java:172)
    at org.loadui.testfx.utils.FXTestUtils$4.call(FXTestUtils.java:168)
    at org.loadui.testfx.utils.FXTestUtils$3.run(FXTestUtils.java:130)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:182)
    at com.sun.javafx.application.PlatformImpl$4$1.run(PlatformImpl.java:179)
    at java.security.AccessController.doPrivileged(Native Method)
    at com.sun.javafx.application.PlatformImpl$4.run(PlatformImpl.java:179)
    at com.sun.glass.ui.InvokeLaterDispatcher$Future.run(InvokeLaterDispatcher.java:76)
    at com.sun.glass.ui.win.WinApplication._runLoop(Native Method)
    at com.sun.glass.ui.win.WinApplication.access$100(WinApplication.java:17)
    at com.sun.glass.ui.win.WinApplication$3$1.run(WinApplication.java:67)
    at java.lang.Thread.run(Unknown Source)
node is not availableNo nodes matched '#lstProject'. 

更改

primaryStage.setScene((Scene) FXMLLoader.load(getClass().getResource(
                "/../GuiMain.fxml")));

primaryStage.setScene(new Scene( FXMLLoader.load(getClass().getResource("/../GuiMain.fxml"))));