1

I'm using TestNG with Selenium. In that, I'm using @AfterMethod and @Test annotations.

In the method that I have used @AfterMethod, I need the method name which has @Test.

For ex:

@Test
public void testmethod() {
  System.out.println("test");
}

@AfterMethod
public void aftermethod() {
   String methodnameofTESTANnnoation=....?
    System.out.println(methodnameof@TESTannotation);
}

Here for method name of @TEST annotation variable, I need the name of @Test annotation method i.e testmethod.

juherr
  • 5,640
  • 1
  • 21
  • 63
Sandeep
  • 47
  • 1
  • 4
  • is there any problem with returning value? make testmethod public String testmethod() and add return("testmethod") for example then try String methodnameofTESTANnnoation= testmethod(); – ReadyFreddy Feb 07 '17 at 07:05
  • 1
    @shmosel Question is about testng. For testng check this out - http://stackoverflow.com/questions/2952202/how-do-i-get-the-name-of-the-test-method-that-was-run-in-a-testng-tear-down-meth?noredirect=1&lq=1 – Grasshopper Feb 07 '17 at 07:09
  • @Grasshopper Good catch. Your link looks like a perfect duplicate. – shmosel Feb 07 '17 at 07:13

1 Answers1

2

TestNG is able to inject Method reference into configuration method. From the documentation:

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, with your sample:

@Test
public void testmethod(){
  System.out.println("test");
}

@AfterMethod
public void aftermethod(Method m){
  String methodNameOfTest = m.getName();
  System.out.println(methodNameOfTest);
}
juherr
  • 5,640
  • 1
  • 21
  • 63