10

When I try to perform unit tests on components which contain JavaFX controls I get a java.lang.IllegalStateException: Toolkit not initialized.

How can components be unit tested which operate with JavaFX controls?

Hannes
  • 5,002
  • 8
  • 31
  • 60

3 Answers3

12

Just declare and initialize a JFX Panel. Like:

@Test
public void test() throws Exception {
    JFXPanel fxPanel = new JFXPanel();
    [.. Begin tests ..]
}

It is the easy way...

Marlord
  • 1,144
  • 2
  • 13
  • 24
  • Thanks for the quick solution. It required the maven dependency: groupid org.openjfx, artifactId javafx-swing. – MRo May 15 '23 at 05:59
7

Add the following dependency to your project

<dependency>
  <groupId>de.saxsys</groupId>
  <artifactId>jfx-testrunner</artifactId>
  <version>1.2</version>
</dependency>

and the following annotation to your test classes

@RunWith(JfxRunner.class)
G. Fiedler
  • 664
  • 4
  • 12
2

Similar to @multiplayer1080 answer but more elegant...

import javafx.application.Platform

@BeforeAll
static void initJfxRuntime() {
    Platform.startup(() -> {});
}

You can go further and declare an abstract class with this method like that:

abstract class FXTest {
    @BeforeAll
    static void initJfxRuntime() {
        Platform.startup(() -> {});
    }
}

and then inherit it when you test JavaFX runtime required stuff:

class SomeGuiTest extends FXTest {
    // ...
}
Vadim
  • 125
  • 7