javatestingjavafxjunittestfx

Can I test stage buttons or Alert dialog with TestFX and JUnit?


I am doing a test class thats verify some things in my window, and i want to know if i can test stage buttons(like know if the window is resizeable, what happend if i click in close request, ...).

Scene scene = new Scene(root);
    //Stage Properties
    stage.setScene(scene);
    stage.setTitle("LogIn");
    stage.setResizable(false);
    stage.setOnShowing(this::handleWindowShowing);
    stage.setOnCloseRequest(this::closeRequest);

I'm really lost in this because i don't know how can I test it, including respective Alerts for example when i click onCloseRequest, shows me a modal alert asking if is he sure with two buttons.

public void closeRequest(WindowEvent event) {
    Alert alert = new Alert(Alert.AlertType.CONFIRMATION);
    alert.setHeaderText("Close confirmation");
    alert.setTitle("Exit Window");
    alert.setContentText("Are you sure that want close the application?");
    alert.initOwner(stage);
    alert.initModality(Modality.WINDOW_MODAL);
    Optional<ButtonType> result = alert.showAndWait();
    if (result.get() == ButtonType.OK) {
        stage.close();
        Platform.exit();
    } else
        event.consume();
}

Is this possible? How can i test it?
Thank you for your help.


Solution

  • I don't think you can verify Close and Minimize windows buttons as they are made by OS, not JavaFX.

    But "Alert" is pretty easy to verify — you can just ask TestFX to work with it despite being in the separate windows:

    verifyThat("OK", NodeMatchers.isVisible());
    verifyThat("Cancel", NodeMatchers.isVisible());
    

    If you want to make sure these elements are from the Alert page, you can try lookup for it first. E.g., here is the check for the alert text:

    Node dialogPane = lookup(".dialog-pane").query();
    from(dialogPane).lookup((Text t) -> t.getText().startsWith("Are you sure"));