Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to register TestExecutionListener in Junit 5 and detect if all tests are executed

Hi I am trying to implement integration test using JUNIT 5 as a framework and we just want to start all the process once before all the test are executed and stop all when all tests are executed.

I found there is no easy way to do this as we have many test class and the BeforeAll and AfterAll method works per test class

What i found , i might be able to do that if i can register my own custom listeners but somehow it didnt work

import com.google.auto.service.AutoService;
        import org.junit.platform.launcher.TestExecutionListener;
        import org.junit.platform.launcher.TestPlan;

@AutoService(TestExecutionListener.class)
public class StateExecutionListener implements TestExecutionListener {

    public void testPlanExecutionStarted(TestPlan testPlan) {
        System.out.println("##########testPlanExecutionStarted "+testPlan.getRoots());
    }

    public void testPlanExecutionFinished(TestPlan testPlan) {
        System.out.println("##########testPlanExecutionStarted "+testPlan.getRoots());
    }

}

Any idea how can we register our own listeners / any other way to detect if all test cases are executed? I use gradle JunitPlatform to run my tests

like image 545
willy Avatar asked Dec 24 '22 02:12

willy


1 Answers

To add on to Sam's answer:

  1. Assuming you have a class MyExecutionListener which implements TestExecutionListener, create a file src/main/resources/META-INF/services/org.junit.platform.launcher.TestExecutionListener
  2. Inside the file put the reference of MyExecutionListener (i.e, com.blah.x.y.z.MyExecutionListener)

An example of this can be found on the official JUnit 5 repository: https://github.com/junit-team/junit5/blob/bd339a570a04d86b92a89e31bbecc59475692e2c/platform-tests/src/test/resources/testservices/META-INF/services/org.junit.platform.launcher.TestExecutionListener

like image 166
TerryA Avatar answered Jan 13 '23 15:01

TerryA