How do I get the name of the test method that was run in a testng tear down method?

Zee Spencer picture Zee Spencer · Jun 1, 2010 · Viewed 42.8k times · Source

Basically, I have a teardown method that I want to log to the console which test was just run. How would I go about getting that string?

I can get the class name, but I want the actual method that was just executed.

public class TestSomething {

    @AfterMethod
    public void tearDown() {
        System.out.println("The test that just ran was: " + getTestThatJustRanMethodName());
    }

    @Test
    public void testCase() {
       assertTrue(1 == 1);
    }
}

...should output to the screen: "The test that just ran was: testCase"

However, I don't know the magic that getTestThatJustRanMethodName should actually be.

Answer

Cedric Beust picture Cedric Beust · Jun 2, 2010

Declare a parameter of type ITestResult in your @AfterMethod and TestNG will inject it:

@AfterMethod
public void afterMethod(ITestResult result) {
  System.out.println("method name:" + result.getMethod().getMethodName());
}