Wait for Platform.RunLater in a unit test

前端 未结 3 487
清酒与你
清酒与你 2021-01-13 06:02

I have a presentation class storing an XYChart.Series object and updating it by observing the model. The Series updating is done by using Platform.runLater(...)

I wa

相关标签:
3条回答
  • 2021-01-13 06:31

    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

    0 讨论(0)
  • 2021-01-13 06:34

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

    0 讨论(0)
  • 2021-01-13 06:40

    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();
        }
    }
    
    0 讨论(0)
提交回复
热议问题