Kotlin检验协程序

zphenhs4  于 2023-01-26  发布在  Kotlin
关注(0)|答案(1)|浏览(94)

我试着测试一个类启动了一个协程,并且协程在线程中正确地做了一些事情,但是我认为我对上下文/调度程序和作用域是如何工作的没有正确的理解,所以这没有按预期工作。

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
    }
}

上面的测试实际上并没有运行完成协程,我不确定我错过了什么,所以任何帮助将不胜感激。

nqwrtyyt

nqwrtyyt1#

您需要确保runTest函数和Janitor使用相同的调度程序,否则您的advanceTimeBy/runCurrent调用无法控制Janitor.cleanUp内部启动的协程的行为。
这应该行得通:

class JanitorTest {
    private val dispatcher = StandardTestDispatcher()

    @Test
    fun `janitor cleans up`() = runTest(dispatcher) {
        val sharedMap = mutableMapOf<Number, String>()
        val janitor = Janitor(sharedMap, 1000L, dispatcher)

        sharedMap[1] = "hello"
        sharedMap[2] = "world"
        janitor.cleanUp(1)

        advanceTimeBy(1000L)
        runCurrent()

        // Expect sharedMap size == 1
    }
}

相关问题