Flutter BLoC Test测试SettingsCubit单元无状态输出失败求解
问题原因
你的报错核心是测试运行时没有捕获到任何Cubit emit的状态,具体由多个错误共同导致:
SettingsState的fromMap方法存在无效逻辑,可能引发解析异常- 你Mock了HydratedBloc的Storage,但没有给对应的读写方法打桩,Cubit初始化时调用Storage方法直接抛出未实现异常,无法正常执行emit逻辑
- blocTest的写法不规范,
expect的预期值也不符合实际emit的内容
修复步骤
1. 修复SettingsState的fromMap逻辑
删除fromMap中完全无效的if (map == map[''])判断,修正后代码如下:
factory SettingsState.fromMap(Map<String, dynamic> map) { return SettingsState( expandNavigation: map['expandNavigation'] ?? false, gpsEnabled: map['gpsEnabled'] ?? false, celsiusEnabled: map['celsiusEnabled'] ?? false, notificationsEnabled: map['notificationsEnabled'] ?? false, breakingNewsNotifications: map['breakingNewsNotifications'] ?? false, trendingNotifications: map['trendingNotifications'] ?? false, liveRemindersNotifications: map['liveRemindersNotifications'] ?? false, sportsNotifications: map['sportsNotifications'] ?? false, ); }
这里额外加了?? fallback默认值,避免存储字段缺失时报错
2. 给MockStorage打桩
在测试的setUp回调中补全Storage方法的mock逻辑:
setUp(() { storage = MockStorage(); // 给读写方法打桩,模拟无历史存储的场景 when(() => storage.read(any())).thenReturn(null); when(() => storage.write(any(), any())).thenAnswer((_) async => {}); HydratedBloc.storage = storage; settingsCubit = SettingsCubit(); });
3. 修正blocTest写法
blocTest默认只收集act执行后emit的新状态,初始状态不会被计入expect,修正后的测试代码如下:
blocTest<SettingsCubit, SettingsState>( 'the cubit should emit a SettingsState with expandNavigation: true when toggleExpandNavigation is called', build: () => SettingsCubit(), act: (cubit) => cubit.toggleExpandNavigation(true), expect: () => [ const SettingsState( expandNavigation: true, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false, breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false, ) ] );
内容的提问来源于stack exchange,提问作者DA_cloak
相关产品推荐
相关产品推荐

