单元测试Arrange阶段设置未生效:isGpsEnabled设为false仍显示true
单元测试中设置
locationRepository.isGpsEnabled = false不生效问题 我在单元测试的Arrange阶段将locationRepository.isGpsEnabled设为false,但调试测试时该值仍显示为true,无法定位问题原因。
相关代码
初始化代码(@Before)
@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) }
调试时观察到locationRepository.isGpsEnabled仍为true(截图显示该字段值为true)
排查方向及解决方案
- 检查FakeLocationRepository的isGpsEnabled属性实现
确认isGpsEnabled是var修饰的可变属性,而非val。如果是使用LiveData/StateFlow这类响应式类型,要确保设置值时正确触发状态更新,没有被其他逻辑覆盖。 - 调整设置isGpsEnabled的时机
当前测试是在ViewModel初始化后才设置isGpsEnabled,如果ViewModel构造或locationUseCases初始化过程中已经读取过该值,后续设置不会生效。可以把locationRepository.isGpsEnabled = false移到locationUseCases和weatherInfoViewModel初始化之前:@Before fun setupViewModel() { preferences = FakePreferences() connectivityObserver = FakeConnectivityObserver() locationRepository = FakeLocationRepository() // 提前设置值 locationRepository.isGpsEnabled = false 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, ) } - 检查ValidateCurrentLocation的逻辑
确认ValidateCurrentLocation用例每次执行时都会读取最新的locationRepository.isGpsEnabled值,而不是在初始化时缓存了该值。如果内部有缓存逻辑,需要修改为实时读取。
内容的提问来源于stack exchange,提问作者Nero Nguyen
相关产品推荐
相关产品推荐

