Basic JUnit test for JavaFX 8

后端 未结 3 859
难免孤独
难免孤独 2020-11-27 19:19

I want to create basic JUnit test for JavaFX 8 application. I have this simple code sample:

public class Main extends Application {
    public static void ma         


        
相关标签:
3条回答
  • 2020-11-27 19:39

    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.

    0 讨论(0)
  • 2020-11-27 19:40

    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()
      {
       //...
      }
    }
    
    0 讨论(0)
  • 2020-11-27 19:47

    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!

    0 讨论(0)
提交回复
热议问题