Sunday, 21 February 2021

Avoiding sleep in Robolectric/Espresso test

I am writing an end-to-end test using Robolectric which triggers an HTTP call to an OkHttp MockWebServer. It looks like this:

val mockServer = MockWebServer()
launchFragmentInHiltContainer<LoginFragment>()

onView(withId(R.id.loginEditText)).perform(typeText("loginId"))
onView(withId(R.id.loginButton)).perform(click())

// At this point, the fragment's viewmodel starts an HTTP request using Retrofit/OkHttp
// The callback causes a LiveData viewmodel to post an event, which the fragment listens
// to, and updates the UI accordingly

val request = mockServer.takeRequest()
assertEquals("/login", req.path)

Thread.sleep(1000)
shadowOf(getMainLooper()).idle()

// Without the two lines above, the test reaches this point before 
// the mock server is done calling back
onView(withId(R.id.loggedInView)).check(matches(isDisplayed()))

How can I make sure that the server response is fully processed after clicking the login button?



from Avoiding sleep in Robolectric/Espresso test

No comments:

Post a Comment