小编Kha*_*l91的帖子

使用 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")
}
Run Code Online (Sandbox Code Playgroud)

postApi.getPosts()直接在内部调用 assertThrows是不可能的,因为它不是一个挂起函数,我尝试使用async,launch

 val exception = testCoroutineScope.async {
            assertThrows<RuntimeException> {
                launch {
                    postApi.getPosts()
                }
            }
        }.await()
Run Code Online (Sandbox Code Playgroud)

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

android unit-testing mockwebserver kotlin-coroutines

8
推荐指数
2
解决办法
4627
查看次数