我想为JavaFX 8应用程序创建基本的JUnit测试。我有这个简单的代码示例:
public class Main extends Application {
public static void main(String[] args) {
Application.launch(args);
}
@Override
public void start(Stage primaryStage) {
primaryStage.setTitle("Tabs");
Group root = new Group();
Scene scene = new Scene(root, 400, 250, Color.WHITE);
TabPane tabPane = new TabPane();
BorderPane borderPane = new BorderPane();
for (int i = 0; i < 5; i++) {
Tab tab = new Tab();
tab.setText("Tab" + i);
HBox hbox = new HBox();
hbox.getChildren().add(new Label("Tab" + i));
hbox.setAlignment(Pos.CENTER);
tab.setContent(hbox);
tabPane.getTabs().add(tab);
}
// bind to take available space
borderPane.prefHeightProperty().bind(scene.heightProperty());
borderPane.prefWidthProperty().bind(scene.widthProperty());
borderPane.setCenter(tabPane);
root.getChildren().add(borderPane);
primaryStage.setScene(scene);
primaryStage.show();
}
}
到目前为止我只有这段代码:
import javafx.application.Application;
import javafx.stage.Stage;
import org.junit.BeforeClass;
public class BasicStart extends Application {
@BeforeClass
public static void initJFX() {
Thread t = new Thread("JavaFX Init Thread") {
@Override
public void run() {
Application.launch(BasicStart.class, new String[0]);
}
};
t.setDaemon(true);
t.start();
}
@Override
public void start(Stage primaryStage) throws Exception {
// noop
}
}
你能告诉我如何为上面的代码创建JUnit测试吗?
答案 0 :(得分:30)
我使用Junit规则在JavaFX线程上运行单元测试。详细信息位于this post。只需从该帖子中复制该类,然后将此字段添加到您的单元测试中。
@Rule public JavaFXThreadingRule javafxRule = new JavaFXThreadingRule();
此代码适用于JavaFX 2和JavaFX 8。
答案 1 :(得分:7)
最简单的方法如下:
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.
}
}
希望它有所帮助!
答案 2 :(得分:4)
基于Brian Blonski的answer我创建了一个JUnit-Testrunner,它基本上做了同样的事情,但在我看来使用起来有点简单。 使用它,您的测试将如下所示:
@RunWith( JfxTestRunner.class )
public class MyUnitTest
{
@Test
public void testMyMethod()
{
//...
}
}