I am using TestNG and have a suite of tests. I want to perform an action before every test method that requires information about the method. As a simple example, say I want to print the name of the method before its executed. I can write a method annotated with @BeforeMethod
. How can I inject parameters into that method?
Take a look at the dependency injection section in the documentation. It states that dependency injection can be used for example in this case:
Any
@BeforeMethod
(and@AfterMethod
) can declare a parameter of typejava.lang.reflect.Method
. This parameter will receive the test method that will be called once this@BeforeMethod
finishes (or after the method as run for@AfterMethod
).
So basically you just have to declare a parameter of type java.lang.reflect.Method
in your @BeforeMethod
and you will have access to the name of the following test name. Something like:
@BeforeMethod
protected void startTest(Method method) throws Exception {
String testName = method.getName();
System.out.println("Executing test: " + testName);
}
There's also a way by using the ITestNGMethod
interface (documentation), but as I'm not exactly sure on how to use it, I'll just let you have a look at it if you're interested.