How do you unit test a JavaFX controller with JUnit

前端 未结 2 397
予麋鹿
予麋鹿 2020-12-10 00:59

What\'s the proper way of initializing the JavaFX runtime so you can unit test (with JUnit) controllers that make use of the concurrency facilities and Platform.runLat

相关标签:
2条回答
  • 2020-12-10 01:55

    Calling launch() from @BeforeClass is a correct approach. Just note that launch() doesn't return control to calling code. So you have to wrap it into new Thread(...).start().

    A 7 years later update:

    Use TestFX! It will take care of launching in a proper way. E.g. you can extend your test from a TestFX's ApplicaionTest class and just use the same code:

    public class MyTest extends ApplicationTest {
    
    @Override
    public void start (Stage stage) throws Exception {
        FXMLLoader loader = new FXMLLoader(
                getClass().getResource("mypage.fxml"));
        stage.setScene(scene = new Scene(loader.load(), 300, 300));
        stage.show();
    }
    

    and write tests like that:

    @Test
    public void testBlueHasOnlyOneEntry() {
        clickOn("#tfSearch").write("blue");
        verifyThat("#labelCount", hasText("1"));
    }
    
    0 讨论(0)
  • 2020-12-10 01:56

    I found this to work,... but only after adding a Thread.sleep(500) after starting the JavaFX application thread. Presumably it takes some time to get the FX environment up and ready (about 200ms on my MacBook Pro retina)

    @BeforeClass
    public static void setUpClass() throws InterruptedException {
        // Initialise Java FX
    
        System.out.printf("About to launch FX App\n");
        Thread t = new Thread("JavaFX Init Thread") {
            public void run() {
                Application.launch(AsNonApp.class, new String[0]);
            }
        };
        t.setDaemon(true);
        t.start();
        System.out.printf("FX App thread started\n");
        Thread.sleep(500);
    }
    
    0 讨论(0)
提交回复
热议问题