android – BottomNavigationView Unit testing with Espresso-ThrowExceptions

Exception or error:
 @Test
 public void testNavigationSelectionListener() {
        homeActivity = homeActivityActivityTestRule.getActivity();
        BottomNavigationView.OnNavigationItemSelectedListener mockedListener =
                mock(BottomNavigationView.OnNavigationItemSelectedListener.class);
        mBottomNavigation.setOnNavigationItemSelectedListener(mockedListener);

        when(mockedListener.onNavigationItemSelected(any(MenuItem.class))).thenReturn(true);
        onView(allOf(withId(R.id.navigation_account),isDisplayed()))
                .perform(click());
}

I have this part of the code that tests bottom navigation item selection. But every time I run I am getting:

androidx.test.espresso.NoMatchingViewException: No views in hierarchy
found matching:

the above error, though the view is present.

Also for Onbackpressed() :

    @Override
    public void onBackPressed() {
        MenuItem homeMenuItem = bottomNavigation.getMenu().getItem(0);
        if (bottomNavigation.getSelectedItemId() == homeMenuItem.getItemId()) {
            super.onBackPressed();
        } else {
            SearchFragment searchFragment = (SearchFragment) search_fragment;
            if (searchFragment.isVisible() && searchFragment.isSearchOptionScreen()) {
                searchFragment.removeSearchData();
            } else {
                int backStackEntry = getSupportFragmentManager().getBackStackEntryCount();
                if (backStackEntry > 0) {
                    for (int i = 0; i < backStackEntry - 1; i++) {
                        getSupportFragmentManager().popBackStackImmediate();
                    }
                }
                bottomNavigation.setSelectedItemId(homeMenuItem.getItemId());
            }
        }
    }

I am getting null pointer exception for menu as the menu is not loaded.

I am totally new to Unit testing. Any help will be much appreciated.

How to solve:

Leave a Reply

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