【问题标题】:Testing suspending functions for exception with JUnit5 assertThrows and MockWebServer使用 JUnit5 assertThrows 和 MockWebServer 测试挂起函数的异常
【发布时间】:2020-09-21 18:08:06
【问题描述】:

我们如何使用 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")
}

直接在assertThrows 内调用postApi.getPosts() 是不可能的,因为它不是暂停功能,我尝试使用asynclaunch

 val exception = testCoroutineScope.async {
            assertThrows<RuntimeException> {
                launch {
                    postApi.getPosts()
                }
            }
        }.await()

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

【问题讨论】:

    标签: android unit-testing kotlin-coroutines mockwebserver


    【解决方案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")
    }
    

    【讨论】:

      【解决方案2】:
      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")
      }
      

      【讨论】:

      • 我更喜欢这个版本,虽然两种解决方案都很好?
      【解决方案3】:

      这是最容易理解的示例

          fun testDividePositiveNumZero(){
          var throwing = ThrowingRunnable { Calculator().divide(1,0) }
          assertThrows(IllegalArgumentException::class.java, throwing)
      }
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2020-10-02
        • 2019-01-27
        • 2018-10-04
        • 1970-01-01
        • 2018-12-10
        相关资源
        最近更新 更多