androidkotlinmockwebserver

MockWebServer - ConnectException: Failed to connect to


When I start my test I get connect exception and I have no idea why.

I found some code others authors and compare code and i didn't find anything wrong. I tried to change ports or remove it and it didn't help me.

@RunWith(AndroidJUnit4::class)
class RideFragmentTest {

@get:Rule
    val activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
    private val mockWebServer = MockWebServer()
    private val PORT = 8607

@Before
    fun init() {
        mockWebServer.start(PORT)
        routeToFragment()
    }

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

@Test
    fun someTest() {
        val dispatcher = object : Dispatcher() {
            @Throws(InterruptedException::class)
            override fun dispatch(request: RecordedRequest): MockResponse {
                when (request.path) {
                    "/something/current" -> {
                        val jsonBody = asset(activityRule.activity, "something.json")
                        return MockResponse().setResponseCode(200).setBody(jsonBody)
                    }
                    "/something/save" -> {
                        return MockResponse().setResponseCode(200)
                    }
                }
                return MockResponse().setResponseCode(404)
            }
        }
        mockWebServer.dispatcher = dispatcher

        assertDisplayed(..., ...)
    }
}
D/OkHttp: --> GET http://127.0.0.1:8607/something/current
D/OkHttp: --> END GET
HTTP FAILED: java.net.ConnectException: Failed to connect to /127.0.0.1:8607

I didn't find any strange logs.


Solution

  • I resolved my question.

    My code should be like this:

    @RunWith(AndroidJUnit4::class)
    class RideFragmentTest {
    
    private val fragment = RideFragment.newInstance()
    
    @get:Rule
        val activityRule: ActivityTestRule<MainActivity> = ActivityTestRule(MainActivity::class.java)
        private val mockWebServer = MockWebServer()
        private val PORT = 8607
    
    @Before
        fun init() {
            mockWebServer.start(PORT)
        }
    
    @After
        fun finish() {
            mockWebServer.shutdown()
        }
    
    @Test
        fun someTest() {
            val dispatcher = code above..
            mockWebServer.dispatcher = dispatcher
            routeToFragment()
    
            assertDisplayed(..., ...)
        }
    
        private fun routeToFragment() = activityRule
           .activity
           .supportFragmentManager
           .beginTransaction()
           .replace(R.id.container, fragment)
           .commit()
    }
    

    i.e. I had to route my fragment after setting dispatcher because mockwebserver had no time for initialization otherwise(i understand so).