Unit testing 如何对合并的DBRoadCastChannel进行单元测试?
我在这里做了一个测试,我试图验证发送到一个合并的DbroadCastChannel的内容(我知道是实验API):Unit testing 如何对合并的DBRoadCastChannel进行单元测试?,unit-testing,kotlin,kotlin-coroutines,Unit Testing,Kotlin,Kotlin Coroutines,我在这里做了一个测试,我试图验证发送到一个合并的DbroadCastChannel的内容(我知道是实验API): @测试 fun myTest()=运行blockingtest{ val results=ArrayList() val myChannel=confollatedbroadcastchannel() myChannel.openSubscription().consumeEach{ 结果。添加(it) } myChannel.send(“你好”) 资产质量(1,结果。大小) }
@测试
fun myTest()=运行blockingtest{
val results=ArrayList()
val myChannel=confollatedbroadcastchannel()
myChannel.openSubscription().consumeEach{
结果。添加(it)
}
myChannel.send(“你好”)
资产质量(1,结果。大小)
}
但当我运行该代码时,我收到一个非法状态异常消息:“此作业尚未完成”。有人知道少了什么吗?我也尝试过使用TestCoroutineDispatcher,但没有成功。因此我想到了我收到的消息,并怀疑“尚未完成的作业”可能就是
。使用我正在执行的每个操作。因此,为了明确起见,我将该操作包装在一个启动(myTestCoroutineDispatcher)
中,并调用cancel
。这似乎不是一种理想的测试方式,但考虑到测试环境并没有真正猜测您的频道何时应该停止接收内容,这是有意义的。不管怎样,你瞧,这是可行的:
@Test
fun myTest() = runBlockingTest {
val results = ArrayList<String>()
val myChannel = ConflatedBroadcastChannel<String>()
launch(testMainDispatcher) {
myChannel.openSubscription().consumeEach {
results.add(it)
cancel()
}
}
myChannel.send("hello")
assertEquals(1, results.size)
}
@测试
fun myTest()=运行blockingtest{
val results=ArrayList()
val myChannel=confollatedbroadcastchannel()
启动(testMainDispatcher){
myChannel.openSubscription().consumeEach{
结果。添加(it)
取消
}
}
myChannel.send(“你好”)
资产质量(1,结果。大小)
}
编辑:为了获得相同的结果,您可以做的另一件事是val myJob=launch{…}
,然后在测试执行结束时,调用myJob.cancel()
,以获得相同的效果。如果您只想从通道获得单个值,您可以始终使用receive
。
由于ConflatedBroadcastChannel
缓存最新的值,您可以这样使用它:
@Test
fun myTest() = runBlockingTest {
val myChannel = ConflatedBroadcastChannel<String>()
myChannel.send("hello")
val subscription = myChannel.openSubscription()
val result = subscription.receive()
subscription.cancel()
assertEquals("hello", result)
}
@测试
fun myTest()=运行blockingtest{
val myChannel=confollatedbroadcastchannel()
myChannel.send(“你好”)
val subscription=myChannel.openSubscription()
val result=subscription.receive()
订阅。取消()
assertEquals(“你好”,结果)
}
请注意,这是特定于合并的DBRoadCastChannel
的,不适用于缓冲的广播频道
@Test
fun myTest() = runBlockingTest {
val myChannel = ConflatedBroadcastChannel<String>()
myChannel.send("hello")
val subscription = myChannel.openSubscription()
val result = subscription.receive()
subscription.cancel()
assertEquals("hello", result)
}