Search code examples
javafxtestfx

How can I prevent duplication in my JavaFX test project


I've got a real simple JavaFX project to teach myself how to write tests with testfx. I can't work out how to prevent myself from having to duplicate my sample.fxml file. The structure of the project is currently:

enter image description here

My Main.java looks like this:

package sample;

import javafx.application.Application;
import javafx.fxml.FXMLLoader;
import javafx.scene.Parent;
import javafx.scene.Scene;
import javafx.stage.Stage;

public class Main extends Application {

    static Stage stage;

    @Override
    public void start(Stage stage) throws Exception {
        Main.stage = stage;
        Parent root = FXMLLoader.load(getClass().getResource("../../resources/sample.fxml"));
        Scene scene = new Scene(root, 300, 275);
        stage.setTitle("FXML Welcome");
        stage.setScene(scene);
        stage.show();
    }

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

I can't access sample.fxml from my test class, and it was just easier to learn testfx with it duplicated - but it's obviously not a way forward. I've also tried creating the scene by calling start() from within my test class but I get an error saying that launch() can't be called more than once.

Has anyone else encountered this and found a way forward?


Solution

  • To avoid duplicating your .fxml files (which I agree is not ideal) I would recommend that you just load the file from src/main/resources. You can do so by using the ClassLoader of your controller(or any other class in non test code).

        String filename = "sample.fxml";
        ClassLoader loader = Controller.class.getClassLoader();
        File file = new File(loader.getResource(filename).getFile());
        Parent root = FXMLLoader.load(loader.getResource(filename));