How to write unit tests for Android fragment Navigation | Unit test android java

Published by inkskull on

Checkout How to write unit tests for Android Navigation Controller | Unit test android java

To test fragment interactions with their NavController in isolation, you can provide a mock NavController inside your test using Mockito. You can then use that mock implementation to verify interactions with it.

Let’s say you are building a trivia game. The game starts with a title_screen and navigates to an in_game screen when the user clicks play.

The fragment representing the title_screen might look something like this:

public class TitleScreen extends Fragment {

    public View onCreateView(@NonNull LayoutInflater inflater,
            @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        return inflater.inflate(R.layout.fragment_title_screen, container, false);

    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        view.findViewById( -> {

To test that the app properly navigates the user to the in_game screen when the user clicks Play, your test needs to verify that this fragment invokes NavController.navigate() with the action

Using a combination of FragmentScenarioEspresso, and Mockito, you can recreate the conditions necessary to test this scenario, as shown in the following example:

public class TitleScreenTestJava {

    public void testNavigationToInGameScreen() {

        // Create a mock NavController
        NavController mockNavController = mock(NavController.class);

        // Create a graphical FragmentScenario for the TitleScreen
        FragmentScenario<TitleScreen> titleScenario = FragmentScenario.launchInContainer(TitleScreen.class);

        // Set the NavController property on the fragment
        titleScenario.onFragment(fragment ->
                Navigation.setViewNavController(fragment.requireView(), mockNavController)

        // Verify that performing a click prompts the correct Navigation action

Categories: Android


Leave a Reply

Your email address will not be published. Required fields are marked *

Social Media Auto Publish Powered By :