我想使用Junit4测试JavaFX的通用视图 - Task。我使用的基本设置取自here。 (我也试过this方法,结果相同)。问题是测试线程似乎通过testDummyTask
方法“运行”,一旦它到达测试功能的末尾,它就会立即取下所有内容。因此,即使任务尚未完成,该阶段仅在一瞬间可见,然后再次消失。
测试类定义如下:
@RunWith(JavaFxJUnit4ClassRunner.class)
public class TaskBarControllerTest {
@Before
public void setUp() throws Exception {
}
@After
public void tearDown() throws Exception {
}
@Test
public void testDummyTask () throws IOException {
final TaskBarController tskBrC = new TaskBarController(new DummyTask());
tskBrC.start();
}
class DummyTask extends Task {
@Override
protected Void call() throws Exception {
final int ITER = 50;
int iterations;
for (iterations = 0; iterations < ITER; iterations++) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
updateMessage("Iteration " + iterations);
updateProgress(iterations, ITER);
// Now block the thread for a short time, but be sure
// to check the interrupted exception for cancellation!
try {
Thread.sleep(100);
} catch (InterruptedException interrupted) {
if (isCancelled()) {
updateMessage("Cancelled");
break;
}
}
}
return null;
}
}
}
方法TaskBarController.start()定义如下:
public void start() throws IOException {
logger.entering(this.getClass().getName(), "start()");
FXMLLoader loader = new FXMLLoader(getClass().getResource(TASKBAR_FXML_RES));
Stage stage = new Stage();
stage.initStyle(StageStyle.UNDECORATED);
loader.setController(this);
Parent root = (Parent) loader.load();
stage.setScene(new Scene(root));
stage.show();
lblProcess.textProperty().bind(task.messageProperty());
pgBar.progressProperty().bind(task.progressProperty());
btnCancel.setOnAction(new EventHandler<ActionEvent>() {
@Override
public void handle(ActionEvent actionEvent) {
task.cancel();
}
});
task.progressProperty().addListener( new ChangeListener<Number>() {
@Override
public void changed(ObservableValue<? extends Number> observableValue, Number number, Number number2) {
lblEta.setText(getEta(number.doubleValue()));
}
});
Thread th = new Thread(task);
th.setDeamon(true);
th.start();
logger.exiting(this.getClass().getName(), "start()");
}
我感谢任何帮助。