Is there a way to get method meta data when using @BeforeMethod in TestNG?

Usman Ismail picture Usman Ismail · Dec 12, 2011 · Viewed 9.4k times · Source

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?

Answer

talnicolas picture talnicolas · Dec 12, 2011

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 type java.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.