If you want to do some operations when your tests are started, passed, finished, failed, or skipped/ignored, you can use Listeners. Both JUnit and TestNG provide us Listeners, and in this article, I will explain how to add JUnit Listeners in your automation framework.

Listeners listen and handle events while your automation code is running. We can add a listener by creating a custom Runner. Then, we can use this custom runner in our test class with @RunWith annotation.

First, let’s write our Listener class by extending JUnit’s RunListener class and overriding its methods. I called our listener class as MyExecutionListener.

MyExecutionListener.java

Second, we need to add the listener to the test execution. We can add the listener by calling the RunNotifier.addListener() method.┬áThis will register our JUnit Listener. I faced with a problem when I tried to use RunListener class’s testRunStarted method. Then, I found a solution that triggers this method after registering the listener in the run method. I wrote a comment about this solution in below code.

MyTestRunner.java

Third, we need to write a test to verify our listener’s functionality. We register our custom runner with @RunWith(MyTestRunner.class) annotation and for alphabetic test execution, we add @FixMethodOrder(MethodSorters.NAME_ASCENDING) annotation.

Extra: Also, you can combine listeners with custom Retry Rule which described in other JUnit article. Thus, when your test fails, it will rerun the failed test according to given retry count.

ListenerExampleTest.java

Result:

junit listeners