7

How can we test a suspending function with MockWebServer that supposed to throw exception?

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")
}

Calling postApi.getPosts() directly inside assertThrows is not possible since it's not a suspending function, i tried using async, launch and

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

but test fails with org.opentest4j.AssertionFailedError: Expected java.lang.RuntimeException to be thrown, but nothing was thrown. for each variation.

Khal91
  • 157
  • 1
  • 8
Thracian
  • 43,021
  • 16
  • 133
  • 222

2 Answers2

8
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")
}
David Buck
  • 3,752
  • 35
  • 31
  • 35
chandima
  • 81
  • 1
  • 2
2

You could just remove the assertThrows, using something like this:

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")
}
CampbellMG
  • 2,090
  • 1
  • 18
  • 27