且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

如何使用 JUnit 对 JavaFX 控制器进行单元测试

更新时间:2023-09-07 17:14:16

@BeforeClass 调用 launch() 是一种正确的方法.请注意 launch() 不会将控制权返回给调用代码.所以你必须把它包装成new Thread(...).start().

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().

7 年后的更新:

使用TestFX!它将负责以适当的方式启动.例如.您可以从 TestFX 的 ApplicionTest 类扩展您的测试,只需使用相同的代码:

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();
}

并像这样编写测试:

@Test
public void testBlueHasOnlyOneEntry() {
    clickOn("#tfSearch").write("blue");
    verifyThat("#labelCount", hasText("1"));
}