android - 如何测试 Kotlin Coroutine actors

标签 android kotlin kotlin-coroutines kotlinx.coroutines.channels

我已经在官方 kotlinx.coroutines docs 中实现了一个 actor .现在我必须在我的仪器测试中测试它们,但我总是得到

IllegalStateException: This job has not completed yet

这是我的测试代码:

@RunWith(AndroidJUnit4::class)
@ExperimentalCoroutinesApi
class ExampleInstrumentedTest {

    @Test
    fun testIncrease() = runBlockingTest {
        val counter = Counter()
        for (i in 0..10) {
            counter.increase()
        }
    }

    @Test
    fun testException() = runBlockingTest {
        val counter = Counter()
        try {
            for (i in 0..11) {
                counter.increase()
            }
            Assert.fail()
        } catch (e: Exception) {
            // All good if the exception was thrown
        }
    }
}

这是 Actor :

sealed class CounterMsg
object IncCounter : CounterMsg()
class GetCounter(val response: CompletableDeferred<Int>) : CounterMsg()

class CounterActor {
    private val actor = GlobalScope.actor<CounterMsg> {
        var counter = 0
        for (msg in channel) {
            when (msg) {
                is IncCounter -> if (counter < 10) counter++ else throw RuntimeException()
                is GetCounter -> msg.response.complete(counter)
            }
        }
    }

    suspend fun send(message: CounterMsg) = actor.send(message)
}

class Counter {
    private val actor = CounterActor()
    suspend fun increase() = actor.send(IncCounter)
}

我的依赖项:

implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:1.3.40"
implementation "org.jetbrains.kotlinx:kotlinx-coroutines-jdk8:1.3.0-M1"
androidTestImplementation "androidx.test.ext:junit:1.1.1"
androidTestImplementation "androidx.test:runner:1.2.0"
androidTestImplementation "org.jetbrains.kotlin:kotlin-test:1.3.40"
androidTestImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:1.3.0-M1"

我已经试过了 GlobalScope.actor<CounterMsg>(Dispatchers.Unconfined)这至少会将第一个测试变为绿色,但异常测试仍然失败。

最佳答案

显然,它正在做一些小的改变:

  • 使用 cancel() 而不是在 actor 中抛出异常
  • 使用runBlocking 代替runBlockingTest

关于android - 如何测试 Kotlin Coroutine actors,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56801937/

相关文章:

android - TabLayout 指示器卡在选项卡之间,内容消失

kotlin - 运行Java -jar时的Dropwizard Kotlin “Main method is not static in class”

field - Kotlin - 如何使外部类的字段只读

android - 在 suspendCancellableCoroutine 中取消回调

java - 尝试为 `coroutine`编写 `handler`模拟,但不起作用

java - 在 Java Android 中加载外部 JSON 文件

java - 如何匹配复杂的字符串?

java - 从网上获取图片并设置到ImageView

java - 在 RecyclerView.Adapter 内部滚动到位置

kotlin - 我如何在惯用的Kotlin中 “wrap”这个不太好的-“by lazy”结果缓存函数调用?