Quick revision
The short answer
We implement TestExecutionListener: executionStarted() stores System.nanoTime() in a ConcurrentHashMap keyed by the test's unique id, executionFinished() computes the duration for identifiers where isTest() is true, and testPlanExecutionFinished() sorts the durations and writes the 20 slowest with their display names to a file. Registering the class in META-INF/services/org.junit.platform.launcher.TestExecutionListener inside a shared test library makes every build that depends on it use the listener without touching any test class.
What to remember
In this answer, we wrote a TestExecutionListener that records a start time per unique id in executionStarted, computes durations for real tests in executionFinished, and writes the 20 slowest with their class and display names in testPlanExecutionFinished. ConcurrentHashMap keeps it correct under parallel execution, a ServiceLoader file in a shared test library registers it for every build without changing tests, and per-fork file names handle builds with several JVMs. Reading the JUnit XML or Open Test Reporting files after the build is a simpler alternative when the reports already contain what we need.
Your turn
Answer it aloud as you would in the interview, or type your answer below. Then show one part at a time and compare.
We implement TestExecutionListener: executionStarted() stores System.nanoTime() in a ConcurrentHashMap keyed by the test's unique id, executionFinished() computes the duration for identifiers where isTest() is true, and testPlanExecutionFinished() sorts the durations and writes the 20 slowest with their display names to a file. Registering the class in META-INF/services/org.junit.platform.launcher.TestExecutionListener inside a shared test library makes every build that depends on it use the listener without touching any test class.
Why this question is asked
Slow tests creep in one at a time, and after a year a suite that used to take two minutes takes twenty. A list of the slowest tests, produced by every build, is the cheapest way to see where the time goes. Interviewers ask for this listener because it shows that we know the JUnit Platform's extension points outside Jupiter, and because the details, parallel execution, which events are tests, where to write the file, are where weaker answers go wrong. In this answer, we will write the listener step by step, register it for all builds through ServiceLoader, look at what changes when tests run in parallel and in several JVMs, and compare it with reading the XML reports after the build.
1Which Hook to Use
Jupiter extensions such as a BeforeEachCallback only see Jupiter tests and must be registered on test classes or through extension auto-detection. A TestExecutionListener works one level lower, at the JUnit Platform, so it sees the events of every engine, Jupiter, Vintage, Spock and others, and the Launcher can load it automatically. That makes it the right hook for a report that must work for every build without changing tests.
The listener receives events with a TestIdentifier, an immutable description of a node in the test tree. Its getUniqueId() is unique within a run, getDisplayName() is the name humans see, and isTest() tells a real test apart from a container such as a class or the engine itself.
2Writing the Listener
We store the start time when a test starts and compute the duration when it finishes. When the whole plan has finished, we sort and write the result.
Notice a few choices. We key everything by unique id, not display name, because two tests in different classes can both be called createsInvoice(), and parameterized invocations share a method name. We use System.nanoTime(), which measures elapsed time, rather than currentTimeMillis(), which can jump when the system clock is adjusted. We look up the parent through the TestPlan so the output says which class a test belongs to. And a failure to write the report is printed, not thrown, because a reporting tool must never break the build it reports on.
3Why the Maps Are Concurrent
With JUnit's parallel execution enabled, executionStarted and executionFinished for different tests are called from different worker threads at the same time. A plain HashMap updated from several threads can lose entries or, in old JDKs, even loop forever. ConcurrentHashMap makes each put and remove safe without a global lock. The plan field is volatile because it is written once on one thread and read on others; it is set before any test starts, so every worker sees it.
6 messages in order. Play them, or step through them one at a time.
Starts and finishes interleave, so each test's start time is looked up by its unique id.
4Registering It for Every Build
We put the listener in a small shared library, for example com.acme:test-reporting, and add a ServiceLoader file to it. Any project that has this library on its test classpath gets the listener automatically, because the Launcher loads all listeners named in such files at startup.
Putting the dependency in the company's parent POM or Gradle convention plugin means teams get the report without doing anything. The listener needs a public no-argument constructor, because ServiceLoader creates it. If a team ever needs to turn it off, the JUnit configuration parameter junit.platform.execution.listeners.deactivate accepts listener class name patterns.
5Several Forks and the Alternative of Reading Reports
There is one more catch. Surefire with forkCount greater than one, and Gradle with maxParallelForks, run tests in several JVMs, and each JVM has its own listener and its own test plan. Each would overwrite the same file. We can include a fork id or the process id in the file name and merge the files afterwards, or let each fork append to a per-fork file.
That is also the moment to consider the alternative: the build tools already write JUnit XML reports with the time of every test case, and JUnit can write the richer Open Test Reporting format when junit.platform.reporting.open.xml.enabled is true. A small script or CI step that reads all report files after the build and prints the slowest 20 needs no code inside the test JVM and handles forks naturally. The listener is better when we want the result inside the build or extra data the reports lack; the report reader is simpler when the reports already have what we need.
6Follow-up questions
Why is isTest() checked in executionStarted and executionFinished?
Because the listener also receives events for containers: the engine, each test class and each parameterized method. A class's duration includes all its tests and its @BeforeAll setup, which is useful in its own right but would dominate a list of slowest tests. Checking isTest() keeps the list to real tests; a second list for containers can be added if class setup time matters.
Does the duration include @BeforeEach and @AfterEach?
Yes. For Jupiter, the test's executionStarted and executionFinished events wrap the whole invocation, including the before-each and after-each callbacks and extensions. Time in @BeforeAll belongs to the class container instead.
7Conclusion
In this answer, we wrote a TestExecutionListener that records a start time per unique id in executionStarted, computes durations for real tests in executionFinished, and writes the 20 slowest with their class and display names in testPlanExecutionFinished. ConcurrentHashMap keeps it correct under parallel execution, a ServiceLoader file in a shared test library registers it for every build without changing tests, and per-fork file names handle builds with several JVMs. Reading the JUnit XML or Open Test Reporting files after the build is a simpler alternative when the reports already contain what we need.
Open with
I would implement TestExecutionListener, which works at the JUnit Platform level, so it sees every engine and can be loaded automatically. In executionStarted, if the identifier is a test, I put System.nanoTime() into a ConcurrentHashMap keyed by the unique id, not the display name, because display names are not unique.
Then, if they want more
In executionFinished, I remove the start time, compute the duration and store it with a readable name, using the TestPlan to add the parent class name. The map must be concurrent because with parallel execution these callbacks come from several worker threads at once.
In testPlanExecutionFinished, I sort the durations in descending order, take 20, format them in milliseconds and write them to a file whose path comes from a system property with a default under target. If writing fails, I log it instead of throwing, because a report must never fail the build.
To register it everywhere without touching tests, I put it in a shared test library with a file META-INF/services/org.junit.platform.launcher.TestExecutionListener containing the class name, and add that library to the company parent POM. With several forks I would include the fork id in the file name.
The alternative is reading the JUnit XML or Open Test Reporting files after the build, which needs no code in the test JVM.
About this answer
- Last updated
- 12 November 2026
- Checked
- Its structure and format are checked automatically. Use it as a carefully prepared study note: where a detail matters, confirm it against the documentation below. What the checks cover
- Where the question comes from
- Written by Scrivio for practice. It is not taken from an interview.
- Official documentation
- JUnit user guide
Report an issue with this answer
Copy the line below and send it to the author with what you found. It carries the address of this page.
Issue with "Write a TestExecutionListener that records the duration of every test and writes the 20...": https://scrivio-interview-library.netlify.app/java/junit/d3378fc3ef/