我有一个实现IInvokedMethodListener的TestNG侦听器。在@BeforeMethod上,我需要设置一些测试上下文,以下是示例:
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,但它也没有提供测试名称。
在我看来,使用侦听器配置测试听起来是错误的——这就是@Before*注释的作用。
我不知道如何通过监听器获得您想要的信息,但使用@BeforeMethod,它很简单:只需在方法签名中添加一个java.reflect.Method类型的参数,TestNG就会注入当前方法,然后您可以询问其名称和其他您想知道的信息。
TestNG注释的所有"魔力"都记录在这里:TestNG依赖注入
HTH-
/Jens
import java.lang.reflect.Method;
public class TestToGetMethodName
{
@BeforeMethod
public void handleTestMethodName(Method method)
{
String testName = method.getName();
}
}
好吧,使用IInvokedMethodListener,beforeInvocation方法为您提供IInvokedMethod方法。
method.getTestMethod.getMethodName()
为您提供方法名称。