Quick revision
The short answer
We write a class that implements BeforeTestExecutionCallback and AfterTestExecutionCallback. Before the test it stores System.nanoTime() in the extension context's Store, under a namespace created from the extension class and the test method; after the test it removes that value, computes the elapsed milliseconds and logs the test if it took more than 500 ms. We register it with @ExtendWith, or for every test through auto-detection, and we use the Store rather than fields so it stays correct under parallel execution.
What to remember
In this answer, we built a JUnit 5 extension that implements BeforeTestExecutionCallback and AfterTestExecutionCallback, stores the start time from System.nanoTime() in the context Store under a namespace made from the extension class and test method, and logs tests slower than 500 ms. We saw why the Store, not a field, keeps it safe with parallel execution, and registered it with @ExtendWith or globally through ServiceLoader with auto-detection enabled.
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 write a class that implements BeforeTestExecutionCallback and AfterTestExecutionCallback. Before the test it stores System.nanoTime() in the extension context's Store, under a namespace created from the extension class and the test method; after the test it removes that value, computes the elapsed milliseconds and logs the test if it took more than 500 ms. We register it with @ExtendWith, or for every test through auto-detection, and we use the Store rather than fields so it stays correct under parallel execution.
Why this question is asked
Slow tests creep into every code base, and a small extension that names them is one of the cheapest ways to keep a build fast. It is also a classic interview exercise because it touches the main parts of the extension API: which callback to choose, where to keep state, and how to register it. In this answer, we will choose the right callbacks, write the extension step by step, see why the Store matters, register it per class and globally, and check the output.
1Choosing the Right Callbacks
JUnit offers two pairs of callbacks around each test. BeforeEachCallback and AfterEachCallback run around the test together with its @BeforeEach and @AfterEach methods. BeforeTestExecutionCallback and AfterTestExecutionCallback run immediately before and after the test method itself, inside the user's setup and teardown.
Which one we want depends on what we measure. To find slow test logic, we use the TestExecution pair, so a slow @BeforeEach that every test shares does not make every test look slow. To measure the full cost of each test including setup, we would use the Each pair. The question asks about the time of each test method, so we choose BeforeTestExecutionCallback and AfterTestExecutionCallback.
- BeforeEachCallback (extensions)
- @BeforeEach methods
- BeforeTestExecutionCallbackrecord start time
- @Test method
- AfterTestExecutionCallbackcompute elapsed, log if over 500 ms
- @AfterEach methods
- AfterEachCallback (extensions)
7 steps in order. Play them, or step through them one at a time.
Our extension measures only the test method, not the shared setup around it.
2Writing the Extension
Here is the full extension. It keeps the start time in the Store and logs with java.lang.System.Logger, so it needs no logging library.
Notice three details. We use System.nanoTime(), not currentTimeMillis(), because nanoTime is a monotonic clock meant for measuring durations and is not affected by the system clock being adjusted. The Namespace combines the extension class and the test method, so our key cannot collide with keys from other extensions or other tests. And remove(START, long.class) both reads and deletes the value, so nothing is left behind; the context also discards its Store when the test finishes.
3Why the Store and Not a Field
The tempting shortcut is a field: private long start; set in before and read in after. It works in a sequential run, but JUnit may use one extension instance for many tests. When parallel execution is enabled, two tests on different threads can run between before and after at the same time, and one overwrites the other's start time, giving nonsense durations.
The Store belongs to the ExtensionContext of the current test, so each test has its own value no matter how many run at once. That is the general rule for extensions: keep them stateless and put per-test state in the Store.
4Registering It and Reading the Output
For one class, we add @ExtendWith(SlowTestExtension.class). For every test in the module, we register it automatically: we list the class name in a ServiceLoader file and enable auto-detection, which is off by default.
Only the slow test is logged. In a real project we might make the threshold configurable through a configuration parameter, read with context.getConfigurationParameter("slow.test.threshold.ms"), and also publish the duration with context.publishReportEntry so it appears in the test reports, not only in logs.
5Follow-up questions
Why not use getRequiredTestClass in the namespace instead of the method?
Using the method makes each test's entry distinct even if some shared Store were involved, which is the pattern the JUnit documentation uses. Since each test has its own ExtensionContext anyway, the class-level namespace would also work, but the method-specific one makes the intent explicit and avoids any collision.
Would @Timeout replace this extension?
No. @Timeout fails a test that runs too long. This extension only reports slow tests without failing them, which suits a gradual cleanup: we find the slowest tests first and fix them without breaking the build.
How would you also measure @BeforeEach time?
I would add a second pair of callbacks, BeforeEachCallback and AfterEachCallback, storing a separate key, and log the difference between the outer and inner durations as setup cost. That shows when the real problem is a slow shared setup rather than slow test logic.
6Conclusion
In this answer, we built a JUnit 5 extension that implements BeforeTestExecutionCallback and AfterTestExecutionCallback, stores the start time from System.nanoTime() in the context Store under a namespace made from the extension class and test method, and logs tests slower than 500 ms. We saw why the Store, not a field, keeps it safe with parallel execution, and registered it with @ExtendWith or globally through ServiceLoader with auto-detection enabled.
Open with
I would implement BeforeTestExecutionCallback and AfterTestExecutionCallback, because those run right around the test method, inside @BeforeEach and @AfterEach, so I measure the test itself and not the shared setup.
Then, if they want more
In beforeTestExecution I get a Store with context.getStore(Namespace.create(getClass(), context.getRequiredTestMethod())) and put System.nanoTime() under a key like start. I use nanoTime because it is monotonic and meant for durations. In afterTestExecution I remove the value from the Store, typed as long, compute elapsed milliseconds, and if it is above 500 I log a warning with the display name and the time.
The important design point is that the start time lives in the Store and not in a field of the extension, because one extension instance can serve many tests, and with parallel execution a field would be overwritten by another test and give wrong numbers. The Store is per test context and is cleaned up automatically.
To register it, I would use @ExtendWith(SlowTestExtension.class) on a class, or for the whole module list it in META-INF/services under the Extension interface and set junit.jupiter.extensions.autodetection.enabled to true. I might also make the threshold a configuration parameter and publish a report entry.
About this answer
- Last updated
- 12 November 2026
- Versions it names
- JUnit 5
- 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 JUnit 5 extension that measures the time of each test method and logs tests...": https://scrivio-interview-library.netlify.app/java/junit/bd9a5d9afe/