Starting JavaFX in Unit Tests

There are great frameworks for all kinds of unit tests, and JavaFX is not an exception here. But sometimes using a full-blown framework is not wanted, so how can JavaFX being started in JUnit? The following source shows how this can get achieved safely.

public class MyTest extends Application {
  private static final CountDownLatch platformIsReady = new CountDownLatch(1);

  @Override public void start(final Stage primaryStage) throws Exception {
    platformIsReady.countDown();
  }

  @BeforeClass public static void setUp() {
    Platform.setImplicitExit(false);
    new Thread(Application::launch).start();
  }

  @AfterClass public static void tearDown() {
    Platform.exit();
  }

  @Before public void waitForPlatform() throws InterruptedException {
    platformIsReady.await();
  }

  @Test public void shouldDoSomething() throws InterruptedException {
    // JavaFX Code here...
  }
}
Advertisements

About Markus Karg

Java Guru with +30 years of experience in professional software development. I travelled the whole world of IT, starting from Sinclair's great ZX Spectrum 48K, Commodore's 4040, over S/370, PCs since legendary XT, CP/M, VM/ESA, DOS, Windows (remember 3.1?), OS/2 WARP, Linux to Android and iOS... and still coding is my passion, and Java is my favourite drug!
This entry was posted in Java, Programming and tagged , . Bookmark the permalink.