dialogtestfx

TestFx - How to test validation dialogs with no ids


I have an application with grid of records and button insert. After clicking insert, there is a form, where you fill in data and click Ok for adding new record to the grid. After clicking Ok, there is validation which fires dialog with error informations, if any of the text fields do not match validation rules. Is there any posible way to test text on the dialog with textFx, if the dialog has no id?


Solution

  • This is an example for Alert based dialog:

    enter image description here

    In your test:

    alert_dialog_has_header_and_content(
        "Removing 'Almaty' location", "Are you sure to remove this record?");
    

    In you helper test class:

    public void alert_dialog_has_header_and_content(final String expectedHeader, final String expectedContent) {
        final javafx.stage.Stage actualAlertDialog = getTopModalStage();
        assertNotNull(actualAlertDialog);
    
        final DialogPane dialogPane = (DialogPane) actualAlertDialog.getScene().getRoot();
        assertEquals(expectedHeader, dialogPane.getHeaderText());
        assertEquals(expectedContent, dialogPane.getContentText());
    }
    
    private javafx.stage.Stage getTopModalStage() {
        // Get a list of windows but ordered from top[0] to bottom[n] ones.
        // It is needed to get the first found modal window.
        final List<Window> allWindows = new ArrayList<>(robot.robotContext().getWindowFinder().listWindows());
        Collections.reverse(allWindows);
    
        return (javafx.stage.Stage) allWindows
                .stream()
                .filter(window -> window instanceof javafx.stage.Stage)
                .filter(window -> ((javafx.stage.Stage) window).getModality() == Modality.APPLICATION_MODAL)
                .findFirst()
                .orElse(null);
    }