我正在尝试为getUser()
函数编写单元测试:
fun getUser(userId:Int) {
// some code...
launchDataOperation { api.getUser(userId) }
}
我可以看到的问题(但不知道如何解决)是launchDataOperation(...)
创建一个协程来调用暂停函数api.getUser
:
fun launchDataOperation(block: suspend () -> Unit): Job {
return coroutineScope.launch {
try {
setLoading(true)
block()
} catch (error: NetworkConnectionException) {
setError(Errors.NETWORK_CONNECTION_ERROR)
} catch (error: DataOperationException) {
setMessage(error.getErrors())
} finally {
setLoading(false)
}
}
}
这是我的考试不及格:
@Test
fun `error message is displayed if api error occurred`() {
val exception = DataOperationException(listOf("FATAL ERROR"))
runBlocking {
`when`(api.getUser(anyInt())).thenAnswer { throw exception }
subject.getUser(userId)
// execution fails if the below line is commented
// this is not the correct way to wait for other coroutines
delay(500) // wait for 500ms till the other coroutines finish
assertThat(subject.messages.value).isEqualTo(exception.getErrors())
}
}