我刚刚开始熟悉Java和JavaFX,并且正在做一个测试JavaFX UI的简单项目。但是,我认为我没有正确地初始化测试,因为我在实例化app对象时得到了一个ExceptionInInitializerError。下面是我的测试文件的相关部分:
public class AppGuiTest extends ApplicationTest {
private App app = new App();
@Override
public void start(Stage stage) throws Exception {
stage.setScene(app.getScene());
stage.show();
stage.toFront();
}
//tests here
}当在app对象中定义标签时,它会出错:
Label message = new Label("Welcome!");下面是我的Gradle文件的相关部分:
plugins {
id 'org.openjfx.javafxplugin' version '0.0.9'
}
dependencies {
implementation 'org.testfx:testfx-junit:4.0.15-alpha'
implementation 'org.loadui:testFx:3.1.2'
implementation 'org.testfx:testfx-junit5:4.0.16-alpha'
implementation 'org.junit.jupiter:junit-jupiter:5.8.1'
implementation 'org.junit.jupiter:junit-jupiter-api:5.8.1'
}
javafx {
version = "17"
modules = [ 'javafx.controls' , 'javafx.base']
}JavaFX部分本身运行得很好。只有当我尝试添加测试时,我才会得到异常。这就是我应该初始化的东西吗?当我从测试文件中删除app变量并注释掉测试的内容时,测试就通过了。如果我没有定义我的应用程序对象,我如何测试UI元素?
我不确定如何修复这个错误,所以任何输入都会非常有帮助。提前感谢!
发布于 2021-12-02 14:43:31
您可以使用JUnit 5 tag @ExtendWith和TestFx ApplicationExtension类。您还应该为start方法使用@Start标记,并在那里初始化Label (或App)。
import javafx.scene.Scene;
import javafx.scene.control.Label;
import javafx.scene.layout.StackPane;
import javafx.stage.Stage;
import org.junit.jupiter.api.Test;
import org.junit.jupiter.api.extension.ExtendWith;
import org.testfx.api.FxRobot;
import org.testfx.framework.junit5.ApplicationExtension;
import org.testfx.framework.junit5.Start;
import static org.testfx.assertions.api.Assertions.assertThat;
@ExtendWith(ApplicationExtension.class)
public class AppGuiTest {
private Label message;
@Start
protected void start(Stage stage) {
message = new Label("Welcome!");
stage.setScene(new Scene(new StackPane(message)));
stage.show();
}
@Test
public void testMessage() {
assertThat(message).hasText("Welcome!");
}
@Test
public void testChangeMessage(FxRobot robot) {
robot.interact(() -> message.setText("Bye!"));
assertThat(message).hasText("Bye!");
}
}你的JUnit 5的Gradle应该是这样的:
dependencies {
testCompile 'org.junit.jupiter:junit-jupiter-api:5.8.2'
testCompile "org.testfx:testfx-junit5:4.0.16-alpha"
testCompile "org.testfx:testfx-core:4.0.16-alpha"
}
plugins {
id 'org.openjfx.javafxplugin' version '0.0.10'
}
javafx {
version = '17'
modules = [ 'javafx.controls', 'javafx.fxml' ]
}https://stackoverflow.com/questions/70195185
复制相似问题