0

I know it's possible to test Retrofit request & response with MockWebServer, like this:

interface AppApi {
    @GET("/time/")
    suspend fun time(): TimeResponse
}
...

class CoinBaseApiClientTest {

    private val mockWebServer = MockWebServer()

    private fun createClient(): AppApi {
        return AppApiFactory.createAppApi(baseUrl = mockWebServer.url("/").toString())
    }

    @Before
    fun setUp() {
        mockWebServer.start()
    }

    @After
    fun tearDown() {
        mockWebServer.shutdown()
    }

    @Test
    fun fetches_time() = runBlocking {
        val timeData: String = """
        {
            "iso": "2015-01-07T23:47:25.201Z",
            "epoch": 1420674445.201
        }
    """
        mockWebServer.enqueue(MockResponse().mockSuccess(200, timeData))

        val timeResponse = createClient().time()
        val recordedRequest = mockWebServer.takeRequest()

        assertThat(recordedRequest.path).isEqualTo("/time/")
        assertThat(timeResponse.iso).isEqualTo("2015-01-07T23:47:25.201Z")
        assertThat(timeResponse.epochAsMillis).isEqualTo(1420674445201)
    }

However, in my case, I only want to test its request payload, such as path, header... without actually execute the time() API (the reason is the actual timeData is really big). So I set mockWebServer.enqueue(MockResponse()) but it doesn't work - it seems require valid TimeResponse JSON data.

Do you know is it possible to only test Retrofit request payload without actually execute the request?

anticafe
  • 6,816
  • 9
  • 43
  • 74

1 Answers1

0

You could just have it return an error status code (i.e. 500) with empty data.

David Liu
  • 9,426
  • 5
  • 40
  • 63
  • With such MockResponse, it would returns `retrofit2.HttpException: HTTP 500 Server Error` and doesn't enter assertion. – anticafe Jul 20 '20 at 12:52