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.html

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.java

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

MyExecutionListener.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.
post

ListenerExampleTest.java

Result:

junit listeners