Search code examples
androidkotlinunit-testingjunit

Unit test arrange not effect


I have already set isGpsEnabled to false, but when I debug the test, it still shows as true. I have no idea why this is happening...

    @Before
    fun setupViewModel() {
        preferences = FakePreferences()
        connectivityObserver = FakeConnectivityObserver()
        locationRepository = FakeLocationRepository()
        weatherRepository = FakeWeatherRepository()
        weatherUseCase = WeatherUseCases(
            getAllWeather = GetAllWeather(weatherRepository),
            convertUnit = ConvertUnit(),
        )
        locationUseCases = LocationUseCases(
            ValidateCurrentLocation(locationRepository, preferences),
        )

        weatherInfoViewModel = WeatherInfoViewModel(
            appPreferences = preferences,
            connectivityObserver = connectivityObserver,
            locationUseCases = locationUseCases,
            weatherUseCases = weatherUseCase,
            locationRepository = locationRepository,
        )
    }
    @Test
    fun firstTimeRunAppAndGrantLocationPermissionButLocationServiceDisabled_navigateToSearch() =
        runTest {
            // Arrange
            locationRepository.isGpsEnabled = false
            assertTrue(weatherInfoViewModel.isInitializing.value)
            weatherInfoViewModel.onFirstTimeLocationPermissionResult(true)
            runCurrent()
            assertEquals(
                WeatherDestinations.SEARCH_ROUTE,
                weatherInfoViewModel.appRoute,
            )
            assertFalse(weatherInfoViewModel.isInitializing.value)
        }

enter image description here


Solution

  • It is a debugging problem; try to make the isGpsEnabled = false in the FakeRepository, and re-check your debug breakpoint, if it is still true, it means something else is changing this value, so check other possible places from where this value is accessed and change.

    Other Possible problems:

    • Check if the isGpsEnabled property is being overridden somewhere else in the code. You can try searching for any other instances where the property is being set or accessed.
    • As said by Logain, Make sure that the locationRepository instance that you are using in your test is the same one that is being used by the WeatherInfoViewModel. Modifications to one copy may not appear in others when creating multiple copies of an object.

    If none of these solutions work, share with us the source code so we can debug it on our end 🙏!