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

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());
}

If you want to get the method name before the test is executed you can use the following:

import java.lang.reflect.Method;

@BeforeMethod
public void nameBefore(Method method)
{
    System.out.println("Test name: " + method.getName());       
}

Just declare a java.lang.reflect.Method parameter.

 @BeforeMethod
 public void beforeTestMethod(Method testMethod){
    System.out.println("Before Testmethod: " + testMethod.getName());       
 }

But TestNG allows you to inject a lot more ;)

  • Any @Before method or @Test method can declare a parameter of type ITestContext.
  • Any @AfterMethod method can declare a parameter of type ITestResult, which will reflect the result of the test method that was just run.
  • Any @Before and @After methods can declare a parameter of type XmlTest, which contain the current tag.
  • 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).
  • Any @BeforeMethod can declare a parameter of type Object[]. This parameter will receive the list of parameters that are about to be fed to the upcoming test method, which could be either injected by TestNG, such as java.lang.reflect.Method or come from a @DataProvider.
  • Any @DataProvider can declare a parameter of type ITestContext or java.lang.reflect.Method. The latter parameter will receive the test method that is about to be invoked.