OkHttp MockWebServer throws java.net.SocketTimeoutException: timeout - exception

145 views Asked by At

I'm using OkHttp's MockWebServer for API mocking in my Android instrumentation tests. It's been effective so far, but I've encountered an issue where making a second call to the same endpoint within the same test case consistently results in a java.net.SocketTimeoutException: timeout error.

In more detail, I need to load a fragment with the web mock server's response. This part is working as expected. However, in the second part of my test, I aim to verify that the displayed data matches the API response. To do this, I need to make a second call to the repository.

I've prepared a simplified test case to illustrate the problem.

@Before
    fun setUp() {
        hiltRule.inject()
        mockWebServer.start()
        val response = SharedUtil.searchAPIMockWebServerResponseWith200()
        mockWebServer.enqueue(response)
    }

@Test
    fun testCalls() {
        runBlocking {
            val firstFlow = productRepo.getMatchedProducts("Search")
            val secondFlow = productRepo.getMatchedProducts("Search")

            // This call works fine
            firstFlow.collectLatest { outcome ->
                if (outcome is Outcome.Success) {
                    println("output one $outcome")
                }


            delay(1000) // to complete the first request
                // this call always throw exception java.net.SocketTimeoutException: timeout
                secondFlow.collectLatest { outcome ->
                    if (outcome is Outcome.Success) {
                        println("output one $outcome ")
                    }
                }

            }
        }
    }

 fun tearDown() {
        mockWebServer.shutdown()
    }

java.net.SocketTimeoutException: timeout

Stacktrace

Thanks in advance

0

There are 0 answers