Middle+
What is the difference between runBlocking, runBlockingTest, and runTest?
sobes.tech AI
Answer from AI
runBlocking: A blocking function that launches a new coroutine and waits for its completion. Mainly used in tests or inmainfunctions where blocking is necessary. Not suitable for production code in UI threads.runBlockingTest(fromkotlinx-coroutines-testbefore version 1.6): A blocking function optimized for testing. UsesTestCoroutineDispatcherby default, allowing control over time and immediate execution of delayed tasks.runTest(fromkotlinx-coroutines-testfrom version 1.6): A non-blocking function designed to replacerunBlockingTest. UsesTestDispatcher. Allows more flexible testing of scenarios with delays and parallel tasks, automatically advancing time.
Main differences:
| Feature | runBlocking |
runBlockingTest (deprecated) |
runTest |
|---|---|---|---|
| Thread blocking | Yes | Yes | No (within tests) |
| Time control | No (uses system time) | Yes (via TestCoroutineDispatcher) |
Yes (via TestDispatcher) |
| Usage in tests | Possible but not optimized | Main purpose | Main purpose |
kotlinx-coroutines-test version |
Not part of the testing library | Up to 1.6 | 1.6+ |
| Replacement | No | runTest |
No |