Wait for Platform.RunLater in a unit test

佐手、 提交于 2019-12-01 06:34:09

The way I solved it is as follows.

1) Create a simple semaphore function like this:

public static void waitForRunLater() throws InterruptedException {
    Semaphore semaphore = new Semaphore(0);
    Platform.runLater(() -> semaphore.release());
    semaphore.acquire();

}

2) Call waitForRunLater() whenever you need to wait. Because Platform.runLater() (according to the javadoc) execute runnables in the order they were submitted, you can just write within a test:

...
commandThatSpawnRunnablesInJavaFxThread(...)
waitForRunLater(...)
asserts(...)`

which works for simple tests

To have it more in AssertJ style syntax, you can do something like this:

    @Test
    public void test() throws InterruptedException {
        // do test here

        assertAfterJavaFxPlatformEventsAreDone(() -> {
            // do assertions here
       }
    }

    private void assertAfterJavaFxPlatformEventsAreDone(Runnable runnable) throws InterruptedException {
        waitOnJavaFxPlatformEventsDone();
        runnable.run();
    }

    private void waitOnJavaFxPlatformEventsDone() throws InterruptedException {
        CountDownLatch countDownLatch = new CountDownLatch(1);
        Platform.runLater(countDownLatch::countDown);
        countDownLatch.await();
    }
}

You could use a CountDownLatch which you create before the runLater and count down at the end of the Runnable

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!