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

Android 使用JUnit5 assertThrows和MockWebServer测试挂起函数的异常,android,unit-testing,kotlin-coroutines,mockwebserver,Android,Unit Testing,Kotlin Coroutines,Mockwebserver,我们如何用应该引发异常的MockWebServer测试挂起函数 fun `Given Server down, should return 500 error`()= testCoroutineScope.runBlockingTest { // GIVEN mockWebServer.enqueue(MockResponse().setResponseCode(500)) // WHEN val exception = assertThrows<Run

我们如何用应该引发异常的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")
}

但是测试失败,原因是
org.opentest4j.AssertionFailedError:预期会抛出java.lang.RuntimeException,但没有抛出任何异常。
对于每个变体。

您可以使用如下方法删除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")
}
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")
}
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")
}