0

Test below is expected to return HttpException but it returns RuntimeException instead.

   @Test
    fun `Server down returns 500 error`() {

        mockWebServer.enqueue(MockResponse().setResponseCode(500))

        val exception: Exception =
            assertThrows(
                HttpException::class.java
            ) {

                githubApi
                    .getRepoList("test")
                    .blockingFirst()

            }

        assertEquals(exception, HttpException::class)

    }

Log for failed test is

INFO: MockWebServer[54339] received request: GET /users/test/repos HTTP/1.1 and responded: HTTP/1.1 500 Server Error Feb 07, 2020 9:20:11 PM okhttp3.mockwebserver.MockWebServer acceptConnections INFO: MockWebServer[54339] done accepting connections: Socket closed Feb 07, 2020 9:20:11 PM okhttp3.mockwebserver.MockWebServer$serveConnection$$inlined$execute$1 runOnce INFO: MockWebServer[54339] connection from /127.0.0.1 failed: java.net.SocketException: Socket closed

org.opentest4j.AssertionFailedError: Unexpected exception type thrown ==> expected: com.jakewharton.retrofit2.adapter.rxjava2.HttpException but was: java.lang.RuntimeException

Thracian
  • 43,021
  • 16
  • 133
  • 222
  • 2
    `blockingFirst` wraps checked exceptions into `RuntimeException` so you have to extract the original exception as its cause. – akarnokd Feb 07 '20 at 18:44
  • @akarnokd Thank you very much. Can you also post it as an answer so i can accept and upvote? If it's not much of a trouble can you post how to extract it from original exception? – Thracian Feb 08 '20 at 05:53

1 Answers1

2

As @akarnokd suggests you need to extract the cause.

assertEquals(exception.cause, HttpException::class)

alternatively you can also test this without blockingFirst like this:

githubApi
    .getRepoList("test")
    .test()
    .assertError(HttpException::class)
LordRaydenMK
  • 13,074
  • 5
  • 50
  • 56