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

前端 未结 5 1667
遇见更好的自我
遇见更好的自我 2020-12-01 08:00

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, bu

5条回答
  •  半阙折子戏
    2020-12-01 08:06

    Another (although not as simple as Cedric's answer) way that TestNG supports this is to register a listener:

    @Listeners({MethodListener.class})
    public class ListenerTest {
    
      @Test
      public void someTest() {
      }
    
    }
    

    Where the listener could look like this:

    public class MethodListener implements IInvokedMethodListener {
    
      @Override
      public void beforeInvocation(IInvokedMethod method, ITestResult testResult) {
    
      }
    
      @Override
      public void afterInvocation(IInvokedMethod method, ITestResult testResult) {
        System.out.println(method.getTestMethod().getMethodName());
      }
    }
    

    This particular listener would print the method name (i.e. someTest) to the console. It would be executed after every executed test.

    If you are generating the testSuite programmatically then you can add the listener as follows instead of adding @Listeners({MethodListener.class}) over each test class

        List listeners = new ArrayList();
        listeners.add(MethodListener.class.getName());
        testSuite.setListeners(listeners);
    

提交回复
热议问题