# coroutines

Jonathan Mew

06/13/2019, 7:40 AM
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.


06/13/2019, 7:46 AM
Don't you get the same problem in your application code? Coroutines might lose their ThreadLocal when resuming there as well.

Jonathan Mew

06/13/2019, 7:54 AM
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
to pass a
argument that adds a survival element to the dispatcher CoroutineContext, which fixed the issue.
thanks for asking a useful question @marstran
👍 1