使用TestNG进行JavaFx 2应用程序的单元测试 [英] Unit testing JavaFx 2 application with TestNG
问题描述
我写了一个相当复杂的JavaFx 2应用程序,我想为此编写一堆单元测试.问题是,当我尝试进行测试时,出现运行时错误,抱怨未初始化的工具包.
I wrote a rather complex JavaFx 2 application for which I'd like to write a bunch of unit tests. Problem is when I try to conduct the tests I get a runtime error complaining about uninitialized toolkit.
据我所知,我应该以某种方式在@BeforeClass方法中调用Application.launch(),但这会导致死锁,因为Application.launch()不会返回调用线程.
From what I can tell I should somehow invoke Application.launch() in a @BeforeClass method but this causes a deadlock as Application.launch() doesn't return to calling thread.
所以问题是我应该如何初始化JavaFx?
So question is how should I initialize JavaFx?
这是无效的代码框架:
public class AppTest extends Application {
@BeforeClass
public void initialize() {
launch(); //this causes a deadlock
}
@Test
public void test1() {
//conduct test here
}
@Test
public void test2() {
//conduct other test here
}
@Override
public void start(Stage arg0) throws Exception {
}
提前谢谢!
推荐答案
From another question here on stackoverflow, I've made myself this little helper class:
import javafx.application.Application;
import javafx.stage.Stage;
public class JavaFXInitializer extends Application {
private static Object barrier = new Object();
@Override
public void start(Stage primaryStage) throws Exception {
synchronized(barrier) {
barrier.notify();
}
}
public static void initialize() throws InterruptedException {
Thread t = new Thread("JavaFX Init Thread") {
public void run() {
Application.launch(JavaFXInitializer.class, new String[0]);
}
};
t.setDaemon(true);
t.start();
synchronized(barrier) {
barrier.wait();
}
}
}
然后可以在@BeforeClass设置方法中轻松使用它:
which can then be used easily in a @BeforeClass setup method:
@BeforeClass
public void setup() throws InterruptedException {
JavaFXInitializer.initialize();
}
这篇关于使用TestNG进行JavaFx 2应用程序的单元测试的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!