JUnit 5 + Apache Surefire 插件 - 如何使用自定义侦听器

问题描述

我正在迈出测试的第一步,所以不要太严格。

如果我使用 Apache Surefire 插件运行我的测试,我如何在 JUnit 5 中使用我的自定义侦听器?它 TestNG 很容易,因为我可以使用注释 @Listeners 或使用测试套件在 .xml 中编写我的侦听器。它 JUnit 我找不到工作决定。

我的自定义监听器:

public class OnrTestListener implements TestExecutionListener {

    private static final Logger LOG = LogManager.getRootLogger();

    @Override
    public void executionSkipped(TestIdentifier testIdentifier,String reason) {
        LOG.info("SKIPPED Test by reason: {}",reason);
    }

    @Override
    public void executionStarted(TestIdentifier testIdentifier) {
        LOG.info("Test {} successfully started.",testIdentifier.getdisplayName());
    }

    @Override
    public void executionFinished(TestIdentifier testIdentifier,TestExecutionResult testExecutionResult) {
        if (testExecutionResult.getStatus() != TestExecutionResult.Status.SUCCESSFUL) {
            String message = "Page screenshot.";
            File screenshot = ScreenshotUtils.takeScreenshot();
            ScreenshotUtils.attachToReportPortal(message,screenshot);
        }
    }

我的附加类 ScreenshotUtils

public class ScreenshotUtils {

    private static final OnrLogger LOG = new OnrLogger();

    private ScreenshotUtils() {
    }

    public static void attachToReportPortal(String message,File screenshot) {
        ReportPortal.emitLog(message,"info",new Date(),screenshot);
    }

    public static File takeScreenshot() {
        return ((TakesScreenshot) DriverFactory.getDriver()).getScreenshotAs(OutputType.FILE);
    }
}

我的测试标记了一些注释(因为我找不到制作套件的决定)并运行我的测试,例如:

mvn clean test -Dgroups=some_tag

我如何尝试使用我的听众:

  1. 我尝试使用注释:

    @ExtendWith(OnrTestListener.class) @Tag("全部") 公共抽象类 BaseUITest { ... }

  2. 在surefire插件中使用配置

                  <configuration>
                     <properties>
                         <property>
                             <name>listener</name>
                             <value>com.google.listeners.OnrTestListener</value>
                         </property>
                         <configurationParameters>
                             junit.jupiter.extensions.autodetection.enabled = true
                             junit.jupiter.execution.parallel.enabled = true
                             junit.jupiter.execution.parallel.mode.default = concurrent
                             junit.jupiter.execution.parallel.mode.classes.default = concurrent
                             junit.jupiter.execution.parallel.config.strategy = fixed
                             junit.jupiter.execution.parallel.config.fixed.parallelism = 5
                         </configurationParameters>
                     </properties>
                 </configuration>
    

但它不起作用。

如果能得到任何帮助,我将不胜感激。谢谢

解决方法

您可以使用 SPI 机制。

将文件 org.junit.platform.launcher.TestExecutionListener 添加到 /src/main/resources/META-INF/services/ 文件夹。

然后将您的侦听器的全名 {your package}.OnrTestListener 添加到此文件中。

将自动应用监听器。