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 {

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

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        view.findViewById(R.id.play_btn).setOnClickListener(v -> {
            Navigation.findNavController(view).navigate(R.id.action_title_screen_to_in_game);
        });
    }
}

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 R.id.action_title_screen_to_in_game.

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

@RunWith(AndroidJUnit4.class)
public class TitleScreenTestJava {

    @Test
    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
        onView(ViewMatchers.withId(R.id.play_btn)).perform(ViewActions.click());
        verify(mockNavController).navigate(R.id.action_title_screen_to_in_game);
    }
}

Categories: Android

0 Comments

Leave a Reply

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

Social Media Auto Publish Powered By : XYZScripts.com