'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
Solution 1:[1]
To have your TestExecutionListener
automatically registered, you have to do that via Java's ServiceLoader
mechanism as described in the JUnit 5 User Guide:
https://junit.org/junit5/docs/current/user-guide/#launcher-api-listeners-custom
Solution 2:[2]
To add on to Sam's answer:
- Assuming you have a class
MyExecutionListener
which implementsTestExecutionListener
, create a filesrc/main/resources/META-INF/services/org.junit.platform.launcher.TestExecutionListener
- 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
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|---|
Solution 1 | Sam Brannen |
Solution 2 | Gerardo Cauich |