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?

- 8,093
- 8
- 50
- 76

- 17,999
- 14
- 83
- 165
3 Answers
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.

- 8,093
- 8
- 50
- 76

- 13,885
- 7
- 36
- 56
-
I'm running my testcase using data provide with multiple dataset , so in the extent report it's showing the same method is running multiple time as many time as manydata we have in excel sheet , so I want to pass the testcase name as a variable (That's in excel) to before method that is in AbstractBaseTestCase class , is there any way to achieve this ?? – Arpan Saini Jul 16 '17 at 08:58
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"}
};
}
}

- 159
- 2
- 2
-
This is exactly what I was looking for, to get parameters when using a data provider. Works perfectly. – Nash N Oct 30 '18 at 21:17
-
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(){
}

- 4,623
- 1
- 42
- 50