【发布时间】:2022-12-23 00:20:13
【问题描述】:
我有一个执行一些工作并立即在挂起函数内返回结果的类,但还包含一个公共 SharedFlow 来更新其他组件有关此工作何时发生的信息(例如,一个执行用户登录然后还提供 Flow 的类在新用户登录时更新监听器:
class ExampleClass(private val api: Api, externalScope: CoroutineScope) {
private val _dataFlow = MutableSharedFlow<String>()
val dataFlow = _dataFlow.shareIn(externalScope, SharingStarted.Lazily)
suspend fun performLogin(): String {
val result = api.getData()
_dataFlow.emit(result)
return result
}
}
interface Api {
suspend fun getData(): String
}
我已经为这门课写了一个测试。测试中的断言通过了,但是和UncompletedCoroutinesError挂了60秒后还是失败了:
class ExampleClassTest {
private val mockApi = mockk<Api> { coEvery { getData() } returns "hello" }
private val testScope = TestScope()
@Test
fun thisTestTimesOutAndFails() = testScope.runTest {
val exampleClass = ExampleClass(mockApi, testScope)
assertEquals("hello", exampleClass.performLogin())
}
}
我如何才能通过测试?
【问题讨论】:
标签: kotlin testing kotlin-coroutines