Home > database >  Co-routines in Kotlin multiplatform project
Co-routines in Kotlin multiplatform project

Time:08-04

I'm trying to use "runTest()" in Kotlin multiplatform. I'm using Jetbrains's "Getting started"-project as an example. (https://kotlinlang.org/docs/multiplatform-library.html)

The problem is that runTest() does not find a coroutine context. It gives me the following build error:

Cannot access class 'kotlin.coroutines.CoroutineContext'. Check your module classpath for missing or conflicting dependencies

Here is my test:

class Base64JvmTest {
@OptIn(ExperimentalCoroutinesApi::class)
@Test
fun testNonAsciiString() {
  runTest {
        val utf8String = "Gödel"
        val actual = Base64Factory.createEncoder().encodeToString(utf8String.toByteArray())
        assertEquals("R8O2ZGVs", actual)
    }
  }
}

In build.gradle.kts, I set the following in kotlin.sourceSets:

val jvmTest by getting {
  dependencies {
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-core:1.6.4")
    implementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
  }
}

Please help me out - what am I missing?

CodePudding user response:

As it turns out, there was an issue with Idea. I added the following dependency to get rid of the error:

dependencies {
  commonTestImplementation("org.jetbrains.kotlinx:kotlinx-coroutines-test:1.6.4")
}

It shouldn't really be needed, as the common tests are not dependent on coroutines, but an acceptable work-around.

CodePudding user response:

you can run runTest following way as documentation is suggested

@Test
fun exampleTest() = runTest {
    val deferred = async {
        delay(1_000)
        async {
            delay(1_000)
        }.await()
    }

    deferred.await() // result available immediately
}

documentation code link

  • Related