Day62 of #100DaysOfCode

Kushagra Kesav
2 min readApr 9, 2022

--

#CodeTogether Day 62/100

Hii folks 🙌

Today I will be continuing the same pathway in which we will test navigation Components.

Unit 3: Navigation

Pathway 2: Introduction to the Navigation component

Source: https://developer.android.com/courses/android-basics-kotlin/course

We will start by creating the test directories and then we will create an instrumentation test class called NavigationTests.kt in the androidTest folder.

  • Then we will add the necessary dependencies as follows:
androidTestImplementation 'com.android.support.test.espresso:espresso-contrib:3.0.2'
androidTestImplementation 'androidx.navigation:navigation-testing:2.3.5'

debugImplementation 'androidx.fragment:fragment-testing:1.3.6'

Now we will sync the project.

  • After that, we will start writing the navigation Component Test. We will specify the test runner.
@RunWith(AndroidJUnit4::class)
  • Now we create a test function called navigate_to_words_nav_component() and create a test instance of the navigation controller.
val navController = TestNavHostController(
ApplicationProvider.getApplicationContext()
)
  • Navigation Components drive the UI using Fragments.
val letterListScenario = launchFragmentInContainer<LetterListFragment>(themeResId =
R.style.Theme_Words)
  • Lastly, we need to explicitly declare which navigation graph we want the nav controller to use for the fragment launched.
letterListScenario.onFragment { fragment ->

navController.setGraph(R.navigation.nav_graph)

Navigation.setViewNavController(fragment.requireView(), navController)
}
  • Now we will trigger the event that prompts the navigation.
onView(withId(R.id.recycler_view))
.perform(RecyclerViewActions
.actionOnItemAtPosition<RecyclerView.ViewHolder>(2, click()))

Today I Learned:

  • How to test Navigation Components.
  • How to avoid repetitive code with the @Before, @BeforeClass, @After, and @AfterClass annotations.

That is all for Day62 ✅

Thanks for reading, See you tomorrow!

If you are reading my #100Days Journey, feel free to drop by ;)

--

--

Kushagra Kesav
Kushagra Kesav

Written by Kushagra Kesav

Developer Relations | Communities | Software Engineering | https://www.linkedin.com/in/kushagrakesav

No responses yet