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

Thr*_*ian 8 android unit-testing mockwebserver kotlin-coroutines

我们如何使用 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.但每个变体的测试都会失败。

小智 9

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


Cam*_*lMG 3

您可以使用如下内容删除断言抛出:

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