gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 13:13:47 25 4
gpt4 key购买 nike

我们如何使用应该抛出异常的 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.对于每个变化。

最佳答案

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")
}

关于android - 使用 JUnit5 assertThrows 和 MockWebServer 测试挂起函数的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62166133/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com