-
Notifications
You must be signed in to change notification settings - Fork 1.9k
Test helper to use Dispatchers.Main without framework dependencies on JVM #568
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Comments
Just pass the dispatcher into your view model constructor (or using a DI framework), then you can use a different dispatcher in unit tests. |
There is one potential enhancement we can discuss (I'm not 100% sure it is a good idea, though). Here it is. We could detect wether you are really running your code under Android, in which case
Then What do you think? |
Zach, agreed, dependency injection (or more likely a service locator pattern here) solves the problem for a specific code base. @elizarov that is an interesting proposal - I see a few ways to consider this (for mockable jar only) After working through them, I'm not sure this is quite the right API. What is needed in the general case of tests with a testing handler is a way to control time. Infinite clocks that reschedule themselves can then be tested by stoping time for example. Building such a handler may be out of the scope of the coroutines library, but it'd be great to put in hooks to switch out the handler with custom implementations. WDYT? Test framework that doesn't support coroutinesAny test written against coroutine code that uses However, a context may be eagerly created at subject creation time (as you demonstrated) so this would need an effective error message. Test framework that supports coroutinesSuch a framework will probably use a custom dispatcher for the reasons listed below. Custom testing dispatcherOne might do this to execute time-delays faster, or to increase the verbosity of logs on failures. I'm not sure how it would detect it's in a What about withContext(Dispatchers.Main)A common pattern I'm seeing is to |
This will be resolved with #749 closing this issue. |
Report version: coroutines 0.26.
In the current implementation of HandlerDispatcher it is not possible to run code that uses Dispatchers.Main in pure-Kotlin tests.
Minimal example:
This leads to a not mocked error.
A typical testing solution on Android is to replace the main looper with an immediate executor in test contexts. For example see InstantTaskExecutorRule from Room.
Taking a look at HandlerDispatcher, it appears it's not possible to avoid the call to
Looper.getMainLooper
as it's used to assignmainHandler
, andHandlerDispatcher
is listed as a sealed class so the only option to get past this import error in the current implementation is to add indirection to references toDispatcher.Main
.The text was updated successfully, but these errors were encountered: