【问题标题】:How to access test method annotations from a TestExecutionListener如何从 TestExecutionListener 访问测试方法注释
【发布时间】:2019-07-17 14:40:59
【问题描述】:

我正在尝试将 Test Management For Jira JUnit Integration 移植到 JUnit5。此模块生成测试运行的 JSON 报告,并使用测试方法上的注释 example 将结果与 Jira 票证相关联。

从 TestExecutionListener 我不确定检索 TestCase 注释的最佳方法是什么。

我使用 TestIdentifier.getSource 查看了反射,并进行了操作以重建方法签名并从那里提取注释,但这种方法感觉很笨拙。

我看到了这个帖子Allow extensions to register TestExecutionListeners,它提出了以下建议:

建议:让您的扩展程序发布 WebDriver bean 的会话 id,例如

String sessionId = ...;
extensionContext.publishReportEntry("webDriverSessionId", sessionId)

在您的TestExecutionListener 中,实现reportingEntryPublished 并将其存储在以TestIdentifier 作为键的Map 中。在 executionFinished 中报告测试结果以及此 Map 中的值。

这种方法看起来很有希望,但我想确保没有其他方法不需要扩展和测试执行侦听器。有没有办法直接在TestExecutionListener中获取测试方法注解信息?

【问题讨论】:

  • 如果您没有具体需要实现 TestExecutionListener,您可以为 JUnit Jupiter 实现 TestWatcher 扩展 API,并通过您的自定义注释(即元注释)注册该扩展使用@ExtendWith(MyExtension.class) 或通过全局注册机制。在您自定义的TestWatcher 扩展中,您可以通过ExtensionContext 访问当前的测试方法,然后在该方法上查找您的注释。
  • @SamBrannen 我有一个使用上述方法的可行解决方案,我确实需要 TestExecutionListener 将报告写入 testPlanExecutionFinished 上的文件。我只需要扩展来捕获与我的注释关联的值。我现在正在尝试扩展它以支持 ParameterizedTest 我查看了从参数中获取值但遇到了Introduce extension API for accessing arguments passed to tests。我现在正在尝试使用 TestReporter 在测试定义中发布 TestCaseKey。
  • 听起来你是在正确的轨道上!
  • 访问@ParameterizedTest 的参数(java.lang.reflect.Parameter) 应该没有任何问题。这应该与任何方法(@Test 等)相同。还是您真的需要访问传递给方法的物理运行时参数
  • @SamBrannen 很抱歉我的回复延迟,感谢您抽出宝贵的时间。我创建了这个gitproject,它展示了我想要完成的事情以及我是否做不到。

标签: junit5 junit5-extension-model


【解决方案1】:

@Alex,以下内容可能会在侦听器中使用... ((MethodSource) testIdentifier.source).javaMethod.getAnnotation(TestCase.class)

【讨论】:

    【解决方案2】:

    似乎您无法从 TestExecutionListener 获取测试注释,但您可以实现 TestWatcher 或例如 AfterEachCallback 并获得这样的自定义注释值:

    import org.junit.jupiter.api.extension.AfterEachCallback;
    import org.junit.jupiter.api.extension.ExtensionContext;
    import org.junit.jupiter.api.extension.TestWatcher;
    
    public class MyExtention implements TestWatcher, AfterEachCallback {
    
    
        @Override public void testSuccessful(ExtensionContext context) {
            if (context.getElement().isPresent() && context.getElement().get().isAnnotationPresent(MyCustomAnnotation.class)) {
                int val = context.getElement().get().getAnnotation(MyCustomAnnotation.class).value();
                // Report on success
            }
        }
    
        @Override public void afterEach(ExtensionContext context) throws Exception {
            if (context.getElement().isPresent() && context.getElement().get().isAnnotationPresent(MyCustomAnnotation.class)) {
                int val = context.getElement().get().getAnnotation(MyCustomAnnotation.class).value();
                // Report each
            }
        }
    }
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-02-20
      • 2015-04-25
      • 2013-03-20
      相关资源
      最近更新 更多