Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

'Toolkit not initialized' exception when unit-testing an JavaFX application

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?

like image 666
Hannes Avatar asked Jul 14 '17 18:07

Hannes


3 Answers

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...

like image 178
multiplayer1080 Avatar answered Nov 17 '22 22:11

multiplayer1080


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)
like image 41
G. Fiedler Avatar answered Nov 18 '22 00:11

G. Fiedler


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 {
    // ...
}
like image 2
Vadim Avatar answered Nov 18 '22 00:11

Vadim