在我的单元测试期间,我想使用Java FX绘制一些数字。现在的问题是,单元测试完成后,JVM和Java FX就会关闭,我无法检查生成的图形(与" test"刚刚启动的情况不同)从主要方法)。所以我的问题是,有没有办法在特定线程完成之前阻止JUnit退出,即在主要方法直接启动测试时复制行为?是的,我知道在一般的单元测试中,绘图很可能不是真正应该完成的事情。 目前我正在做这样的事情:
//@ContextConfiguration(classes = {DummyConfig.class })
//@RunWith(SpringJUnit4ClassRunner.class)
public class MainViewTest {
private boolean fromMain = false;
// starting the "test" from main does not require explicit waiting for
// for the JavaFX thread to finish .. I'd like to replicate this
// behaviour in JUnit (by configuring JUnit, not my test or application code)
public static void main(String [] args){
new MainViewTest(true).test();
}
public MainViewTest(){}
private MainViewTest(boolean fromMain){
this.fromMain = fromMain;
}
@Test
public void test() {
//do some tests....
//plot some results...
PlotStage.plotStage(new QPMApplication() {
@Override
public Stage createStage() {
Stage stage = new Stage();
StackPane root = new StackPane();
Scene scene = new Scene(root, 300, 300);
stage.setTitle("Stage");
stage.setScene(scene);
stage.setOnCloseRequest(new EventHandler<WindowEvent>(){
@Override
public void handle(WindowEvent event) {
Platform.exit();
}
});
return stage;
}
});
System.out.println("Stage started");
// how to get rid of this block (or using a countdownlatch) but
// still waiting for the threads to finish?
Set<Thread> threads = Thread.getAllStackTraces().keySet();
if (!fromMain) {
System.out.println("checking threads...");
for (Thread thread : threads) {
if (thread.getName().contains("JavaFX")) {
try {
thread.join();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
}
}
}
问题在于我想要摆脱这个令人讨厌的块,等待所有JavaFX平台被明确退出。 我很欣赏有关使用倒计时锁存器而不是明确加入Java FX线程的答案。然而,这仍然需要我明确地停止当前线程。但是,我宁愿&#34;告诉&#34; JUnit以某种方式等待JavaFX线程完成。
基本上我正在寻找的是一种告诉JUnit在我的测试方法中没有任何阻塞代码的情况下等待特定线程的方法。
附录:最小运行示例的必要类
public class PlotStage {
public static boolean toolkitInialized = false;
public static void plotStage(QPMApplication stageCreator) {
if (!toolkitInialized) {
Thread appThread = new Thread(new Runnable() {
@Override
public void run() {
Application.launch(InitApp.class);
}
});
appThread.start();
}
while (!toolkitInialized) {
try {
Thread.sleep(100);
} catch (InterruptedException e) {
e.printStackTrace();
}
}
Platform.runLater(new Runnable() {
@Override
public void run() {
Stage stage = stageCreator.createStage();
stage.show();
}
});
}
public static class InitApp extends Application {
@Override
public void start(final Stage primaryStage) {
toolkitInialized = true;
}
}
}
public interface QPMApplication {
public abstract Stage createStage();
}
答案 0 :(得分:1)
1
初始化。Stage
后,请调用countDown()
。await()
等待Stage
关闭。示例:
CountDownLatch cdl = new CountDownLatch(1);
// TODO show the stage and do not forget to add cdl.countDown() to your
// stage.setOnCloseRequest
cdl.await();
备选方案#1:
使用JavaFX Junit Rule直接在FX应用程序线程上执行所有操作。
备选方案#2:
使用TestFX,根据我从更新后的说明中读到的内容,它最适合。