繁体   English   中英

TestFX 和 Junit5 的 ExceptionInInitializerError

[英]ExceptionInInitializerError with TestFX and Junit5

我刚刚熟悉 Java 和 JavaFX,并且正在开发一个简单的项目来测试 JavaFX UI。 但是,我认为我没有正确初始化测试,因为我在实例化应用程序 object 时遇到了 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 
}

在应用程序 object 中定义 label 时会出错:

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 变量并注释掉测试的内容时,测试通过了。 如果我没有定义我的应用程序 object,我该如何测试 UI 元素?

我不确定如何修复此错误,因此任何输入都会非常有帮助。 提前致谢!

您可以使用JUnit 5标签@ExtendWithTestFx ApplicationExtension class。 您还应该使用@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' ]
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM