android - 如何测试 Kotlin 协程演员
问题描述
我已经在官方kotlinx.coroutines 文档中实现了一个演员。现在我必须在我的仪器测试中测试它们,但我总是得到
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
}
}
}
这是演员:
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)
至少将第一个测试变为绿色,但异常测试仍然失败。
解决方案
我通过添加以下规则解决了:
@get: Rule
var instantExecutorRule = InstantTaskExecutorRule()
推荐阅读
- c++ - 更新文件请求导致 404
- javascript - 将表 Google Script 交互式 Google Sheet 覆盖到 Google Docs,反之亦然
- python - 从列表中的每个值中提取第一个单词
- css - HTML/CSS - 居中浮动内容
- sql-server - JTDS 尝试(但失败)在应用程序启动时重新创建已经存在的表
- javascript - 使用 Xpath 修改 XML 数据的表单
- java - Java 使用扫描仪逐字读取动态日志文件
- docker - ASP.NET Core 微服务
- sql - 基于 3 个表之间的关系从 IBM DB2 查找表中提取值
- bash - 仅在有时推送“没有这样的文件或目录”