Basic JUnit test for JavaFX 8

╄→гoц情女王★ 提交于 2019-11-27 01:28:07
Brian Blonski

I use a Junit Rule to run unit tests on the JavaFX thread. The details are in this post. Just copy the class from that post and then add this field to your unit tests.

@Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();

This code works for both JavaFX 2 and JavaFX 8.

The easiest aproach is the following:

import javafx.application.Platform;
import javafx.embed.swing.JFXPanel;
import javafx.stage.Stage;

import org.junit.Test;

public class BasicStart {

    @Test
    public void testA() throws InterruptedException {
        Thread thread = new Thread(new Runnable() {

            @Override
            public void run() {
                new JFXPanel(); // Initializes the JavaFx Platform
                Platform.runLater(new Runnable() {

                    @Override
                    public void run() {
                        new Main().start(new Stage()); // Create and
                                                        // initialize
                                                        // your app.

                    }
                });
            }
        });
        thread.start();// Initialize the thread
        Thread.sleep(10000); // Time to use the app, with out this, the thread
                                // will be killed before you can tell.
    }

}

Hope it helps!

Based on Brian Blonski 's answer I created a JUnit-Testrunner, that does essentially the same thing, but is a bit simpler to use in my opinion. Using it, your test would look like this:

@RunWith( JfxTestRunner.class )
public class MyUnitTest
{
  @Test
  public void testMyMethod()
  {
   //...
  }
}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!