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.
Below example shows how to get params when using data provider, using Object[] array in @BeforeMethod.
public class TestClass {
@BeforeMethod
public void beforemethod(Method method, Object[] params){
String classname = getClass().getSimpleName();
String methodName = method.getName();
String paramsList = Arrays.asList(params).toString();
}
@Test(dataProvider = "name", dataProviderClass = DataProvider.class)
public void exampleTest(){...}
}
public class DataProvider {
@DataProvider(name = "name")
public static Object[][] name() {
return new Object[][]{
{"param1", "param2"},
{"param1", "param2"}
};
}
}
Below example explains how you can get the method name and class name in your before Method
@BeforeMethod
public void beforemethod(Method method){
//if you want to get the class name in before method
String classname = getClass().getSimpleName();
//IF you want to get the method name in the before method
String methodName = method.getName()
}
@Test
public void exampleTest(){
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With