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

xesrikrc  于 2023-10-20  发布在  Java
关注(0)|答案(4)|浏览(165)

初始化JavaFX运行时的正确方法是什么,这样您就可以(使用JUnit)对使用并发功能和Platform.runLater(Runnable)的控制器进行单元测试?
@BeforeClass方法调用Application.launch(...)会导致死锁。如果没有调用Application.launch(...),则会抛出以下错误:

java.lang.IllegalStateException: Toolkit not initialized
    at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:121)
    at com.sun.javafx.application.PlatformImpl.runLater(PlatformImpl.java:116)
    at javafx.application.Platform.runLater(Platform.java:52)
    at javafx.concurrent.Task.runLater(Task.java:1042)
    at javafx.concurrent.Task.updateMessage(Task.java:987)
    at com.xyz.AudioSegmentExtractor.call(AudioSegmentExtractor.java:64)
    at com.xyz.CompletionControllerTest.setUp(CompletionControllerTest.java:69)
    at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
    at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:57)
    at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
    at java.lang.reflect.Method.invoke(Method.java:601)
    at org.junit.runners.model.FrameworkMethod$1.runReflectiveCall(FrameworkMethod.java:44)
    at org.junit.internal.runners.model.ReflectiveCallable.run(ReflectiveCallable.java:15)
    at org.junit.runners.model.FrameworkMethod.invokeExplosively(FrameworkMethod.java:41)
    at org.junit.internal.runners.statements.RunBefores.evaluate(RunBefores.java:27)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:76)
    at org.junit.runners.BlockJUnit4ClassRunner.runChild(BlockJUnit4ClassRunner.java:50)
    at org.junit.runners.ParentRunner$3.run(ParentRunner.java:193)
    at org.junit.runners.ParentRunner$1.schedule(ParentRunner.java:52)
    at org.junit.runners.ParentRunner.runChildren(ParentRunner.java:191)
    at org.junit.runners.ParentRunner.access$000(ParentRunner.java:42)
    at org.junit.runners.ParentRunner$2.evaluate(ParentRunner.java:184)
    at org.junit.runners.ParentRunner.run(ParentRunner.java:236)
    at org.eclipse.jdt.internal.junit4.runner.JUnit4TestReference.run(JUnit4TestReference.java:50)
    at org.eclipse.jdt.internal.junit.runner.TestExecution.run(TestExecution.java:38)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:467)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.runTests(RemoteTestRunner.java:683)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.run(RemoteTestRunner.java:390)
    at org.eclipse.jdt.internal.junit.runner.RemoteTestRunner.main(RemoteTestRunner.java:197)

后续:这是我根据@SergeyGrinev的建议一直在使用的主题。

... // Inside test class

public static class AsNonApp extends Application {
    @Override
    public void start(Stage primaryStage) throws Exception {
        // noop
    }
}

@BeforeClass
public static void initJFX() {
    Thread t = new Thread("JavaFX Init Thread") {
        public void run() {
            Application.launch(AsNonApp.class, new String[0]);
        }
    };
    t.setDaemon(true);
    t.start();
}
... // controller tests follow...
yh2wf1be

yh2wf1be1#

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

7年后更新:

使用TestFX!它将负责以适当的方式发射。例如,您可以从TestFX的ApplicationTest类扩展您的测试,并使用相同的代码:

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"));
}
kfgdxczn

kfgdxczn2#

我发现这个工作,.但只有在启动JavaFX应用程序线程后添加Thread.sleep(500)之后。大概需要一些时间才能让FX环境准备就绪(在我的MacBook Pro视网膜上大约200毫秒)

@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);
}
aamkag61

aamkag613#

这对我来说也适用于测试使用JavaFX并发结构(如javafx.concurrent.Task)的代码。与其他解决方案相比,它不需要显式的线程管理或提供虚拟Application

@BeforeAll
public static void setUpJavaFXRuntime() throws InterruptedException {
    CountDownLatch latch = new CountDownLatch(1);
    Platform.startup(() -> {
        latch.countDown();
    });
    latch.await(5, TimeUnit.SECONDS);
}

@AfterAll
public static void tearDownJavaFXRuntime() throws InterruptedException {
    Platform.exit();
}
khbbv19g

khbbv19g4#

这就是你所需要的:

@BeforeAll
static void initJfxRuntime() {
    try {
        Platform.runLater(() -> {});
    } catch (Exception ex) {
        Platform.startup(() -> {});
    }
}

相关问题