首页 > 解决方案 > 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("all") 公共抽象类 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>
    

但它不起作用。

如果有任何帮助,我将不胜感激。谢谢

标签: junitjunit5maven-surefire-plugin

解决方案


您可以使用 SPI 机制。

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

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

监听器将被自动应用。


推荐阅读