Custom Coroutine Contexts: Seamless TestDispatcher injection
summary
Explains a concrete technique that avoids constructor dispatcher injection by adding a custom CoroutineContext element that supplies a DispatcherProvider and makes production code call currentDispatchers.io, so tests can inject a TestDispatcher via runTest; reproduces the example where a 5s timeout test becomes ~69ms. Offers a tiny open-source helper (runTest wrapper and context element) to apply this across a codebase, with caveats for libraries that hardcode dispatchers and for code that breaks structured concurrency.
AI-written summary · about
chapters (15)
- 0:00Introduction
- 1:08Talk overview
- 3:54TestDispatchers in unit tests
- 6:00Dispatcher replacement options
- 9:54Limitations of current solutions
- 11:38TestDispatcher injection issue
- 12:02CoroutineContext internals
- 16:18Access patterns in CoroutineContext
- 19:12Context inheritance and evolution
- 25:14Custom CoroutineContext element
- 26:39TestDispatcher in production
- 27:43Custom runTest solution
- 28:46Advantages of new approach
- 30:52Future plans
- 31:47Q&A




