使用Mocktail模拟WeatherRepository时遇No method stub错误求助
解决Mocktail模拟WeatherRepository时的"Bad state"错误
错误原因
你当前代码里的mockWeatherRepository是真实的WeatherRepository实例,而非你定义的MockWeatherRepository模拟类实例。当你在when()中调用mockWeatherRepository.getCurrentWeather()时,实际执行的是真实类的方法,Mocktail无法捕获这个调用,因此抛出Bad state: No method stub was called from within when()错误。
修复步骤
- 将
mockWeatherRepository的类型改为MockWeatherRepository - 在
setUp中初始化模拟实例,而非真实的WeatherRepository - 确保
when()针对模拟实例的方法进行桩定义
修复后的完整测试代码
import 'package:flutter_test/flutter_test.dart'; import 'package:mocktail/mocktail.dart'; import 'package:weather_app/bloc/weather_bloc.dart'; import 'package:weather_app/data/repository/weather_repository.dart'; import 'package:weather_app/models/weather_model.dart'; import 'package:bloc_test/bloc_test.dart'; class MockWeatherRepository extends Mock implements WeatherRepository {} void main() { late MockWeatherRepository mockWeatherRepository; setUp(() { // 初始化模拟实例,而非真实Repository mockWeatherRepository = MockWeatherRepository(); }); String cityName = "New Delhi"; WeatherModel weather = WeatherModel( currentTemp: 20.0, currentSky: 'Rain', currentPressure: 10, currentWindSpeed: 20.0, currentHumidity: 10); blocTest( 'Get weather', build: () { // 针对模拟实例的方法定义桩 when(() => mockWeatherRepository.getCurrentWeather(cityName)) .thenAnswer((_) async => weather); return WeatherBloc(mockWeatherRepository); }, act: (bloc) => bloc.add(WeatherFetched()), expect: () => [ isA<WeatherLoading>(), isA<WeatherSuccess>() ], ); }
额外说明
- 你之前定义的
MockWeatherRepository类没有被实际使用,这是核心问题 - 不需要再初始化
WeatherDataProvider,因为我们直接模拟了Repository层,跳过了底层数据提供者的依赖
内容的提问来源于stack exchange,提问作者Anish Hemachandran
相关产品推荐
相关产品推荐

