How do you unit test a JavaFX controller with JUnit

前端 未结 2 398
予麋鹿
予麋鹿 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"));
    }
    

提交回复
热议问题