如何在 Junit 5 中注册 TestExecutionListener 并检测是否执行了所有测试

wil*_*lly 4 java junit java-8 junit5

嗨,我正在尝试使用 JUNIT 5 作为框架来实现集成测试,我们只想在执行所有测试之前启动所有过程,并在执行所有测试时停止所有过程。

我发现没有简单的方法可以做到这一点,因为我们有很多测试类,并且 BeforeAll 和 AfterAll 方法适用于每个测试类

我发现,如果我可以注册自己的自定义侦听器,我也许可以做到,但不知何故它不起作用

import com.google.auto.service.AutoService;
        import org.junit.platform.launcher.TestExecutionListener;
        import org.junit.platform.launcher.TestPlan;

@AutoService(TestExecutionListener.class)
public class StateExecutionListener implements TestExecutionListener {

    public void testPlanExecutionStarted(TestPlan testPlan) {
        System.out.println("##########testPlanExecutionStarted "+testPlan.getRoots());
    }

    public void testPlanExecutionFinished(TestPlan testPlan) {
        System.out.println("##########testPlanExecutionStarted "+testPlan.getRoots());
    }

}
Run Code Online (Sandbox Code Playgroud)

知道我们如何注册我们自己的监听器/任何其他方式来检测是否所有测试用例都被执行?我使用 gradle JunitPlatform 来运行我的测试

Ter*_*ryA 10

添加到 Sam 的答案:

  1. 假设您有一个MyExecutionListener实现的类TestExecutionListener,创建一个文件src/main/resources/META-INF/services/org.junit.platform.launcher.TestExecutionListener
  2. 在文件内放置MyExecutionListener(ie, com.blah.x.y.z.MyExecutionListener)的引用

可以在官方 JUnit 5 存储库中找到这样的示例: https: //github.com/junit-team/junit5/blob/bd339a570a04d86b92a89e31bbecc59475692e2c/platform-tests/src/test/resources/testservices/META-INF/services/ org.junit.platform.launcher.TestExecutionListener


Sam*_*nen 6

TestExecutionListener自动注册,您必须通过ServiceLoaderJUnit 5 用户指南中所述的Java机制来完成:

https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom