JavaFX测试随机失败

时间:2017-09-24 18:05:46

标签: java multithreading unit-testing javafx junit

我有一个JUnit Test Class,如下所示:

public class HelloWorldApplicationTest {

private static TextArea mEditor = new HelloWorldApplication().getmEditor();

@BeforeClass
public static void initToolKit() throws InterruptedException {

    final CountDownLatch latch = new CountDownLatch(1);
    SwingUtilities.invokeLater(() -> {
        new JFXPanel(); // initializes JavaFX environment
        latch.countDown();
    });

    // That's a pretty reasonable delay... Right?
    if (!latch.await(5L, TimeUnit.SECONDS))
        throw new ExceptionInInitializerError();

}


@Test
public void testA(){
    mEditor.setText("111");
    assertTrue(mEditor.getText().equals("111"));
    mEditor.setText("qqq");
    assertTrue(mEditor.getText().equals("qqq"));
    mEditor.setText("eee");
    assertTrue(mEditor.getText().equals("eee"));
    mEditor.setText("aaa");
    assertTrue(mEditor.getText().equals("aaa"));
    mEditor.setText("aaa");
    assertTrue(mEditor.getText().equals("aaa"));
}

@Test
public void testB(){
    mEditor.setText("222");
    assertTrue(mEditor.getText().equals("222"));
    mEditor.setText("222");
    assertTrue(mEditor.getText().equals("222"));
    mEditor.setText("222");
    assertTrue(mEditor.getText().equals("222"));
    mEditor.setText("111");
    assertTrue(mEditor.getText().equals("111"));
}

@Test
public void testC(){
    mEditor.setText("333");
    assertTrue(mEditor.getText().equals("333"));
    mEditor.setText("333");
    assertTrue(mEditor.getText().equals("333"));
    mEditor.setText("TTT");
    assertTrue(mEditor.getText().equals("TTT"));
    mEditor.setText("333");

}

}

如果删除initToolkit方法,测试将在Linux / OSX中传递,但在Windows抛出中失败:

java.lang.ExceptionInInitializerError: null
        at com.sun.glass.ui.Screen.getScreens(Screen.java:70)
        at com.sun.glass.ui.Screen.getMainScreen(Screen.java:61)
        at com.sun.javafx.font.PrismFontFactory.getSystemFontSize(PrismFontFactory.java:1911)

或者,mEditor不是一个静态变量。

java.lang.RuntimeException: Internal graphics not initialized yet
at com.sun.glass.ui.Screen.getScreens(Screen.java:70)
at com.sun.glass.ui.Screen.getMainScreen(Screen.java:61)
at com.sun.javafx.font.PrismFontFactory.getSystemFontSize(PrismFontFactory.java:1911)

(参见:JavaFX Test That fails in Windows and works in OSX and Linux

如果我添加initToolkit方法,JavaFX环境会被初始化,但测试开始随机失败,有时测试通过! 当我使用单个处理器在Windows VM上进行测试时,测试通过,这可以描述静态编辑器上的多线程问题? 我已经尝试过同步块(synchronised(mEditor)),通过引用这个线程初始化JavaFX环境:How do you unit test a JavaFX controller with JUnit,但我总是最终得到这种随机行为,其中一些测试通过,一些测试失败如果再次运行,测试可以随机传递或失败。

0 个答案:

没有答案