我们如何使用应该抛出异常的 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")
}
postApi.getPosts()
无法直接在内部调用 ,assertThrows
因为它不是暂停功能,我尝试使用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.
但是对于每个变体,测试都失败了。