Skip to content

Instantly share code, notes, and snippets.

@RicardoBelchior
Last active March 13, 2019 19:08
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save RicardoBelchior/8243dca237d20d89484a32d23b545680 to your computer and use it in GitHub Desktop.
Save RicardoBelchior/8243dca237d20d89484a32d23b545680 to your computer and use it in GitHub Desktop.
Fragment test example, using AndroidX
private lateinit var scenario: FragmentScenario<SearchFragment>
private val parentActivity = mock<SearchFragment.ParentActivity>()
@Before
fun setUp() {
// Prepare fake data for SearchFragment
// ...
// Setup the FragmentScenario and attach any required mock data to it
scenario = launchFragmentInContainer<SearchFragment>(Bundle.EMPTY, R.style.Theme_AppCompat_Light)
scenario.onFragment {
it.setParentActivity(parentActivity)
}
}
@Test
fun `when loading, progressbar is displayed`() {
whenSearchReturns(Single.never())
scenario.onFragment {
it.performQuery("brexit")
it.progressBar().shouldBeVisible()
}
}
/////////////////////////////////////////////////////////////////
private fun whenSearchReturns(singleResult: Single<List<Tag>>) {
given(searchRequest.execute(any())).willReturn(singleResult)
}
private fun SearchFragment.performQuery(query: String) {
searchView()
.setQuery(query, true)
}
// Or, if you declare these Views in the fragment w/ package-protected level,
// you can call those fields directly.
private fun SearchFragment.searchView() =
view!!.findViewById<SearchView>(R.id.search_card_view_search_view)
private fun SearchFragment.progressBar() =
view!!.findViewById<View>(R.id.fragment_search_progress_bar)
private fun View.shouldBeVisible() {
visibility shouldEqualTo View.VISIBLE
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment