David Bakin’s programming blog.

A TestNG Listener can register itself with TestNG

The TestNG documentation lists 5 ways of registering a TestNG listener.  Here’s a sixth, that’s sometimes useful:

If your listener is specific to a test suite (it’s not really general purpose) or if you don’t mind dropping the source into each test suite, then relying on the fact that the @Listeners annotation makes the named listener(s) available to the entire suite (not just the one annotated class) you can make your listener itself be a test class!

  • Put your listener class in the same place as the rest of the test classes in your suite (or name it in your testng.xml, or whatever).
  • Put an @Listeners annotation in front of the class, referring to itself.
  • Add a method annotated with @Test inside the listener class.

Now the listener class will be identified as a test class, and it’s @Listener annotation will be respected, and thus it itself will be a listener.

Note that your test method in the listener class can have @Test(enabled=false) (so it doesn’t pollute your results) and it still works!