Search code examples
androidmockingmockitotestcase

Create test case for the method who modify its input and pass to mock object


I am using Mockito for writing unit test case in Android. I am stuck into one method where I am modify Object and pass it to mocked method, Not able to understand how to write unit test case for this

 Class LocationViewModel{

        private LocationInteractor locationInteractor;
         LocationViewModel (LocationInteractor locationInteractor){
            this.locationInteractor =locationInteractor;
         }

          @Override
        public Single<List<String>> getRecentLocations( LocationViewType locationViewType) {
            return locationInteractor.getUpdatedRecentLocation(getRecentLocationFilter(locationViewType),locationViewType);
        }

        private Map<String, String[]> getRecentLocationFilter(LocationViewType locationViewType) {
               LocationFilter locationfilter = new LocationFilter();
                if (locationViewType == LocationViewType.DEFAULT_LOCATIONS) {
                  return locationFilter.getRecentDefaultLocationFilter();
                } else if (locationViewType == SETTING_LOCATIONS) {
                  return locationFilter.getRecentSettingLocationFilter();
                } else if (locationViewType == LocationViewType.INVENTORY_LOCATION) {
                  return locationFilter.getRecentSettingLocationFilter();
                } else {
                  return locationFilter.getRecentCurrentLocationFilter();
                }
        }
   }

   Class LocationViewModelTest{

      @Mock private LocationInteractorContract mockLocationInteractor;
      private LocationViewModelContract locationViewModel;

      @Before
      public void setUp() {
        initMocks(this);
        locationViewModel = new LocationViewModel(mockLocationInteractor)
      }

      @Test
      public void getRecentLocationsList_check_for_Null() {

        when(mockLocationInteractor.getUpdatedRecentLocation(anyMap(),LocationViewType.SETTING_LOCATIONS)) ......Line 1
            .thenReturn(Single.error(NullPointerException::new));

        locationViewModel
            .getRecentLocations(LocationViewType.SETTING_LOCATIONS)
            .test()
            .assertFailure(NullPointerException.class);
      }

   }   

When I use anyMap() in Line no 1 it throws - org.mockito.exceptions.misusing.InvalidUseOfMatchersException:

When I use new HashMap<>() in Line no 1 it throws NullPointerException

Want to write test case for method - getRecentLocations where getRecentLocationFilter is private method


Solution

  • For the InvalidUseOfMatchersException, the reason is probably that you have to use either all values or all matchers. For example:

    when(mockLocationInteractor.getUpdatedRecentLocation(anyMap(), any())