侦听器中获取测试方法名称

侦听器中获取测试方法名称

本文介绍了是否可以在配置阶段在 TestNG 侦听器中获取测试方法名称?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个实现 IInvokedMethodListener 的 TestNG 侦听器.在@BeforeMethod 上,我需要设置一些测试上下文,示例如下:

I have a TestNG listener that implements IInvokedMethodListener. On @BeforeMethod I need to setup some test context, here is the example:

public class ThucydidesInvokedMethodListener implements IInvokedMethodListener2 {

    public void beforeInvocation(final IInvokedMethod method, final ITestResult testResult) {

    boolean areBeforeMethods = method.getTestMethod().getTestClass().getBeforeTestMethods().length > 0;
    if ((areBeforeMethods && method.getTestMethod().getTestClass().getBeforeTestMethods()[0] == method.getTestMethod()) ||
            !areBeforeMethods && method.isTestMethod()) {

        final ThucydidesTestContext context = new ThucydidesTestContext(testResult);
        testResult.setAttribute(contextKey(), context);
        context.before();
    }
}

但我还需要一个将在 BeforeMethod 之后执行的测试名称,以便在报告中使用此测试名称.这可以使用 TestNG 吗?我也试过 IInvokedMethodListener2,它也有 ITestContext,但它也没有提供测试名称.

but also I need a test name that will be executed after the BeforeMethod to use this test name in the reports. Is this possible using TestNG?Also I've tried IInvokedMethodListener2 that additionally has ITestContext, but it doesn't provide the test name as well.

推荐答案

在我看来,使用侦听器配置测试是错误的 - 这就是 @Before* 注释的用途.

Using a listener for configuring your tests sounds wrong to me - that is what the @Before* annotations are for.

我不知道如何使用侦听器获取您想要的信息,但是使用@BeforeMethod 很简单:只需将 java.reflect.Method 类型的参数添加到您的方法签名中,TestNG 将注入您可以使用的当前方法然后询问它的名称以及您想知道的所有其他信息.

I do not know how to get your desired information with a listener, but with @BeforeMethod it is simple: Just add a parameter of type java.reflect.Method to your method signature and TestNG will inject the current method which you can then ask for its name and everything else you want to know.

此处记录了 TestNG 注释的所有魔法":TestNG 依赖项注射

All "magic' for the TestNG annotations is documented here:TestNG dependency injection

HTH

/詹斯

这篇关于是否可以在配置阶段在 TestNG 侦听器中获取测试方法名称?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

07-31 12:55