0

我想用 testFx 测试我的 JavaFX 应用程序。用户填写登录表单,单击按钮 logInBtn,应用程序显示警报并打开客户面板。测试运行并显示警报,但是在这个场景应该切换到另一个场景之后,我得到了很多错误。

public class App extends Application {
private static Scene scene;
@Override
public void start(Stage stage) throws IOException {
    scene = new Scene(loadFXML("logIn"));
    stage.setScene(scene);
    stage.show();
}

public static void setRoot(String fxml) throws IOException {
    scene.setRoot(loadFXML(fxml));
}

private static Parent loadFXML(String fxml) throws IOException {
    FXMLLoader fxmlLoader = new FXMLLoader(App.class.getClassLoader().getResource( fxml + ".fxml"));
    return fxmlLoader.load();
}

public static void main(String[] args) {
    launch();
}

}

我的测试课:

public class AppTest extends ApplicationTest {
@Override
public void start(Stage stage) throws Exception {
    Parent mainNode = FXMLLoader.load(App.class.getClassLoader().getResource("logIn.fxml"));
    stage.setScene(new Scene(mainNode));
    stage.show();
    stage.toFront();
}
@Test 
public void signUpTest() {
    //filling the logIn form out
    clickOn("#logInBtn");
}

登录按钮: <Button fx:id="logInBtn" onAction="#logIn"

登录方法:

@FXML
private void logIn() throws IOException {
    ... /*grabbing data from the form fields, db manipulation*/
    if (personDbController.isLogged(mail, password)) {
        Alert alert = new Alert(Alert.AlertType.INFORMATION);
        alert.setContentText("You are successfully logged in!");
        App.setRoot("catalogCustomer");
    } 
}

我收到这些错误:

--- Exception in Async Thread --- 
java.lang.reflect.InvocationTargetException: null
java.lang.IllegalStateException: Location is not set.
javafx.fxml.FXMLLoader.loadImpl(FXMLLoader.java:2434)
javafx.fxml.FXMLLoader.load(FXMLLoader.java:2409)
App.loadFXML(App.java:36) (this is method loadFXML in App class)
App.setRoot(App.java:31)
 - java.lang.RuntimeException: java.lang.RuntimeException: 
 - java.lang.reflect.InvocationTargetException
at org.testfx.util.WaitForAsyncUtils.---- Delayed Exception: (See Trace Below) ----(WaitForAsyncUtils.java:0)
Caused by: java.lang.RuntimeException: java.lang.reflect.InvocationTargetException
Caused by: java.lang.IllegalStateException: Location is not set.

我猜它发生 bcs testFX 无法正确访问 JavaFX 线程,所以我无法在场景之间切换。我正在查看 testFX 文档 - 如何在场景之间切换,但我一无所获。有人知道我该如何解决吗?

已解决:问题是 setRoot 函数无法执行,因为场景在基本类中不存在(场景是在测试类线程中创建并打开的,而不是在主线程中)。我添加AppTest.setRoot("catalogAdmin");到测试类,现在它可以工作了

4

0 回答 0