Retrieve test name on TestNG

Stan Kurilin picture Stan Kurilin · Dec 21, 2011 · Viewed 37.7k times · Source

Can I retrieve currently running test name like in JUnit (using getName() or rules)?

@Test
public void fooBar(){
     System.out.println(magic()); //should print "fooBar"
}

P.S. I don't want use some self-written tool based on stack traces.

Answer

Dmitry picture Dmitry · Aug 30, 2012

I found better solution with @BeforeMethod annotation:

import java.lang.reflect.Method;

public class Test
{ 

    @BeforeMethod
    public void handleTestMethodName(Method method)
    {
        String testName = method.getName(); 
        ...
    }

    ...
}

(based on solution from this thread)