我试着测试一个类启动了一个协程,并且协程在线程中正确地做了一些事情,但是我认为我对上下文/调度程序和作用域是如何工作的没有正确的理解,所以这没有按预期工作。
class Janitor (
private val sharedMap: MutableMap<Number, String>,
private val delayMs: Long,
private val dispatcher: CoroutineDispatcher = newSingleThreadContext("JanitorThread"),
) {
private val janitorScope = CoroutineScope(dispatcher)
fun cleanUp(key: Number) {
janitorScope.launch(CoroutineName("Janitor Cleaning Up key:[$key]")) {
println("Launching coroutine in JanitorThread to clean up $key after $delayMs")
delay(delayMs)
sharedMap.remove(key)
println("Done removing $key from sharedMap after $delayMs")
}
}
}
class JanitorTest {
@Test
fun `janitor cleans up`() = runTest {
val sharedMap = mutableMapOf<Number, String>()
val janitor = Janitor(sharedMap, 1000L, StandardTestDispatcher())
sharedMap[1] = "hello"
sharedMap[2] = "world"
janitor.cleanUp(1)
advanceTimeBy(1000L)
runCurrent()
// Expect sharedMap size == 1
}
}
上面的测试实际上并没有运行完成协程,我不确定我错过了什么,所以任何帮助将不胜感激。
1条答案
按热度按时间nqwrtyyt1#
您需要确保
runTest
函数和Janitor
使用相同的调度程序,否则您的advanceTimeBy
/runCurrent
调用无法控制Janitor.cleanUp
内部启动的协程的行为。这应该行得通: