3

我们如何使用应该抛出异常的 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.但是对于每个变体,测试都失败了。

4

3 回答 3

3
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")
}
于 2020-09-13T04:52:39.540 回答
1

您可以使用以下内容删除 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")
}
于 2020-06-03T08:00:09.967 回答
0

这是最容易理解的样本

    fun testDividePositiveNumZero(){
    var throwing = ThrowingRunnable { Calculator().divide(1,0) }
    assertThrows(IllegalArgumentException::class.java, throwing)
}
于 2021-12-01T21:14:12.867 回答