Carrying thread local data through a test class #4938
-
I am implementing improved leak detection for the netty project test suite. For this purpose, it is necessary to clearly determine which test class (and associated resource scope) a resource is allocated in. At the end of the test class (AfterAll), a junit5 extension will verify that all resources allocated in the class have been released. To implement this, I use an InheritableThreadLocal created in BeforeAll. However, I had some issues with this approach when running tests concurrently. JUnit uses a ForkJoinPool which may lead to test methods running on different threads, or methods from other test classes running on the thread a particular class was started on. As a temporary solution, I assign the thread local in BeforeAll and in BeforeEach, with proper handling for nesting. You can look at the implementation in this PR. But this seems like a hack. If a test were to run a ForkJoinTask itself for example, this would not be enough. Is there a better solution to this, or is a better solution planned? Running tests using virtual threads could help for example, and there is an issue (#3442) for this. A more compatible solution would be to use a non-ForkJoin thread pool for test execution, but I'm not sure this is desirable. |
Beta Was this translation helpful? Give feedback.
Replies: 1 comment 3 replies
-
I think there's no way around assigning the |
Beta Was this translation helpful? Give feedback.
I think there's no way around assigning the
ThreadLocal
on the thread that will invoke the test. I think it might be easier to implementInvocationInterceptor
, though, because that would avoid having to do the nesting with the help of theExtensionContext.Store
. Instead, a try-finally block could be used to set and then reset theThreadLocal
. Moreover, this could be extended to not just supportinterceptTestMethod
, but also all kind of lifecycle methods, etc.