【发布时间】:2020-09-21 18:08:06
【问题描述】:
我们如何使用 MockWebServer 测试应该抛出异常的挂起函数?
fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {
// GIVEN
mockWebServer.enqueue(MockResponse().setResponseCode(500))
// WHEN
val exception = assertThrows<RuntimeException> {
testCoroutineScope.async {
postApi.getPosts()
}
}
// THEN
Truth.assertThat(exception.message)
.isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}
直接在assertThrows 内调用postApi.getPosts() 是不可能的,因为它不是暂停功能,我尝试使用async、launch 和
val exception = testCoroutineScope.async {
assertThrows<RuntimeException> {
launch {
postApi.getPosts()
}
}
}.await()
但每个变体的测试都以org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown. 失败。
【问题讨论】:
标签: android unit-testing kotlin-coroutines mockwebserver