I'm working on Android instrumentation tests with MockWebServer of Square. Here are the codes that I'm trying to run. However, I'm getting error from Okhttp client, when I ran the test. I've added network configurations
HTTP FAILED: java.net.ConnectException: Failed to connect to localhost/127.0.0.1:8080
@UninstallModules(
UrlModule::class
)
@HiltAndroidTest
@RunWith(AndroidJUnit4::class)
class MainActivityTest {
@get:Rule
val hiltRule = HiltAndroidRule(this)
private val mockWebServer = MockWebServer()
@Inject
lateinit var okHttp: OkHttpClient
private lateinit var okHttp3IdlingResource: OkHttp3IdlingResource
@Before
fun setup() {
hiltRule.inject()
okHttp3IdlingResource = OkHttp3IdlingResource.create("okhttp", okHttp)
IdlingRegistry.getInstance().register(okHttp3IdlingResource)
IdlingRegistry.getInstance().register(TestIdlingResource.countingIdlingResource)
mockWebServer.dispatcher = MockServerDispatcher().RequestDispatcher()
mockWebServer.start()
}
@Test
fun screenIsReady() {
val scenario = launchActivity<MainActivity>()
onView(withId(R.id.recyclerViewMovies)).check { view, noViewFoundException ->
if (noViewFoundException != null) {
throw noViewFoundException
}
val recyclerView = view as RecyclerView
assertEquals(20, recyclerView.adapter?.itemCount)
}
scenario.close()
}
@Module
@InstallIn(SingletonComponent::class)
class FakeBaseUrlModule {
@Provides
@Singleton
fun provideUrl(): String = "http://localhost:8080/"
}
@After
fun teardown() {
mockWebServer.shutdown()
IdlingRegistry.getInstance().unregister(okHttp3IdlingResource)
IdlingRegistry.getInstance().unregister(TestIdlingResource.countingIdlingResource)
}
I'm waiting your comments. Thank you.
I noticed my mistake. The solution is pretty easy. I should have started the server with port number like mockWebServer.start(8080).
Regards