flutter - Flutter:单元测试一个 Cubit 问题
问题描述
我一直在尝试为我的 cubit 设置单元测试,但 bloc 测试似乎有问题。只是尝试检查值的初始状态在常规测试中效果很好,但是一旦我尝试使用 bloc 测试进行相同的事情,它就会吐出失败,实际是 [0] 处的空列表,我不确定我做错了什么。互联网上没有任何东西对这个错误有帮助。
//passes
test('initial state of SettingsCubit', () {
expect(
settingsCubit.state,
SettingsState(
notificationsEnabled: false,
gpsEnabled: false,
celsiusEnabled: false,
expandNavigation: false,
breakingNewsNotifications: false,
trendingNotifications: false,
liveRemindersNotifications: false,
sportsNotifications: false));
});
//fails
blocTest(
'initial state of SettingsCubit',
build: () => SettingsCubit(),
expect: () => [
SettingsState(
expandNavigation: false,
gpsEnabled: false,
celsiusEnabled: false,
notificationsEnabled: false,
breakingNewsNotifications: false,
trendingNotifications: false,
liveRemindersNotifications: false,
sportsNotifications: false,
)
],
);
错误:
package:bloc_test/src/bloc_test.dart 193:9 testBloc.<fn>
===== asynchronous gap ===========================
dart:async _asyncThenWrapperHelper
package:bloc_test/src/bloc_test.dart testBloc.<fn>
dart:async runZonedGuarded
package:bloc_test/src/bloc_test.dart 172:9 testBloc
package:bloc_test/src/bloc_test.dart 140:11 blocTest.<fn>
package:bloc_test/src/bloc_test.dart 139:26 blocTest.<fn>
Expected: [
SettingsState:SettingsState(expandNavigation: false, gpsEnabled: false, celsiusEnabled: false, notificationsEnabled: false,breakingNewsNotifications: false, trendingNotifications: false, liveRemindersNotifications: false, sportsNotifications: false)
]
Actual: []
Which: at location [0] is [] which shorter than expected
SettingsCubit 和 SettingsState 代码位于: Flutter BLoC 测试失败
解决方案
如果你想测试你的 Cubit 的初始状态,你应该使用第一种方法(适合你的方法)。
文档中描述了相同测试的第二个版本(blocTest
一个)不起作用的原因bloc_test
:
[expect] 是一个可选项
Function
,它返回一个Matcher
在bloc
[act] 被执行后被测试期望发出的 a。
这意味着,您应该将所有状态更改放在expect
方法中。但是现在,您只是创建了一个 BLoC,之后没有执行任何操作,您的状态不会改变,因此实际结果 - 预期状态更改的列表 - 是空的。
推荐阅读
- python - 如何在 Pandas 中将字符串列转换为序号?
- laravel - 将参数从 @extends 布局发送到控制器 Laravel
- css - React 导入样式文件的快捷方式
- regex - 正则表达式删除在谷歌表格中留下名字的名字标题
- python - 如何在 Python / Tkinter 文本中添加文本
- python - 旋转具有多列的 pandas 数据框
- laravel - 在 VueJS 中将 laravel 路由作为道具传递时出错
- list - 如何将列表链接到 if else?扑
- selenium - Helper 包通常应该包含哪些类/函数 - Selenium & cucumber
- scala - 重构/组合解码器