I have a query about ThreadLocals, coroutines and ...
# coroutines
j
I have a query about ThreadLocals, coroutines and JUnit5 extensions
We use JUnit5 for unit testing and there is a ThreadLocal in a dependency library that we would like to pre-set to different values for certain unit tests. We are using ktor and for some tests it seems that the ThreadLocal loses its value (presumably due to resuming coroutines?). Is there some way to configure the scope to restore the ThreadLocal value for a given test? I have found resources for how to restore them outside of a unit test scenario, but not sure how to translate that across into a JUnit5 extension. I'd prefer to avoid the boilerplate of a wrapper function in every such test method.
m
Don't you get the same problem in your application code? Coroutines might lose their ThreadLocal when resuming there as well.
j
Hmm no we don't but interesting point. I believe it gets cached early on in a separate non-thread-local variable in the application. Perhaps I could pre-populate the cache though. I'll try that.
The reason it doesn't happen in our application is because within each ktor handler everything is blocking, which is fine for our use case for the time being. In the end I changed the call to
withTestApplication
to pass a
configure
argument that adds a survival element to the dispatcher CoroutineContext, which fixed the issue.
thanks for asking a useful question @marstran
👍 1