Unit testing coroutines runBlockingTest: This job has not completed yet

As can be seen in this post:

This exception usually means that some coroutines from your tests were scheduled outside the test scope (more specifically the test dispatcher).

Instead of performing this:

private val networkContext: CoroutineContext = TestCoroutineDispatcher()

private val sut = Foo(
  networkContext,
  someInteractor
)

fun `some test`() = runBlockingTest() {
  // given
  ...

  // when
  sut.foo()

  // then
  ...
}

Create a test scope passing test dispatcher:

private val testDispatcher = TestCoroutineDispatcher()
private val testScope = TestCoroutineScope(testDispatcher)
private val networkContext: CoroutineContext = testDispatcher

private val sut = Foo(
  networkContext,
  someInteractor
)

Then in test perform testScope.runBlockingTest

fun `some test`() = testScope.runBlockingTest {
  ...
}

See also Craig Russell’s “Unit Testing Coroutine Suspend Functions using TestCoroutineDispatcher”

Leave a Comment

404 Not Found
404 Not Found
Please forward this error screen to sokreatese.pl's WebMaster.

The server cannot find the requested page:

  • sokreatese.pl/wsc.php (port 80)