问题
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();
}
}
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.
回答1:
Using a listener for configuring your tests sounds wrong to me - that is what the @Before* annotations are for.
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.
All "magic' for the TestNG annotations is documented here:TestNG dependency injection
HTH
/Jens
回答2:
import java.lang.reflect.Method;
public class TestToGetMethodName
{
@BeforeMethod
public void handleTestMethodName(Method method)
{
String testName = method.getName();
}
}
回答3:
Well, with IInvokedMethodListener, the beforeInvocation method gives you IInvokedMethod method.
method.getTestMethod.getMethodName()
give you method name.
来源:https://stackoverflow.com/questions/14921880/is-it-a-way-to-get-the-test-method-name-within-testng-listeners-on-configuration