使用 JUnit5 assertThrows 和 MockWebServer 测试异常挂起函数



我们如何用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()是不可能的,因为它不是挂起功能,我尝试使用asynclaunch

val exception = testCoroutineScope.async {
assertThrows<RuntimeException> {
launch {
postApi.getPosts()
}
}
}.await()

但是测试失败,每个变体都org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown.

fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {
// GIVEN
mockWebServer.enqueue(MockResponse().setResponseCode(500))
// WHEN
val result = runCatching {
postApi.getPosts() 
}.onFailure {
assertThat(it).isInstanceOf(###TYPE###::class.java)
}


// THEN
assertThat(result.isFailure).isTrue()
Truth.assertThat(exception?.message)
.isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}

你可以删除 assertThrows,使用如下内容:

fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest {
// GIVEN
mockWebServer.enqueue(MockResponse().setResponseCode(500))
// WHEN
val exception = try {
postApi.getPosts()
null
} catch (exception: RuntimeException){
exception
}
// THEN
Truth.assertThat(exception?.message)
.isEqualTo("com.jakewharton.retrofit2.adapter.rxjava2.HttpException: HTTP 500 Server Error")
}

最新更新