Sobes.tech
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 in main functions where blocking is necessary. Not suitable for production code in UI threads.
  • runBlockingTest (from kotlinx-coroutines-test before version 1.6): A blocking function optimized for testing. Uses TestCoroutineDispatcher by default, allowing control over time and immediate execution of delayed tasks.
  • runTest (from kotlinx-coroutines-test from version 1.6): A non-blocking function designed to replace runBlockingTest. Uses TestDispatcher. 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
What is the difference between runBlocking… - sobes.tech