flutter - 与 expect() 函数比较时,包含 List 的 Dartz Right 会抛出错误
问题描述
像这样的简单代码
expect(Right(['Two', 'Three']), equals(Right(['Two', 'Three'])));
抛出错误:
ERROR: Expected: Right<dynamic, List>:<Right([Two, Three])>
Actual: Right<dynamic, List>:<Right([Two, Three])>
我究竟做错了什么?两个列表是相同的,并且都具有相等的元素。
解决方案
Dart 默认检查引用相等性,在这里您正在组合两个具有相等值但不相等引用的数组。常量列表将按照您的预期运行,而运行时定义的列表则不会。
final a = ['Two', 'Three'] == ['Two', 'Three']; // false
final b = const ['Two', 'Three'] == const ['Two', 'Three']; // true
这可能会令人困惑,因为这会通过:
expect(['Two', 'Three'], equals(['Two', 'Three']));
测试库具有迭代器的默认匹配器,并将进行深度检查以匹配列表中的所有字符串,因此上述通过。数据类型不是这种情况Right
,它将回==
退到 -operator 并因此失败,因为它将返回 false ,如上所示。
Dartz 有一个列表实现(不可变),用于检查是否会成功或使用 const 的深度相等,如上所述:
final a2 = ilist('Two', 'Three') == ilist('Two', 'Three') // true
expect(Right(ilist(['Two', 'Three'])), equals(Right(ilist(['Two', 'Three']))));
expect(Right(const ['Two', 'Three']), equals(Right(const ['Two', 'Three'])));
推荐阅读
- javascript - 如何在类星体测试中运行单文件测试
- ruby-on-rails - 如何检查用户名和密码是否在数据库中可用或没有从 Ruby on rails 中的邮递员那里获取输入
- json - 打字稿中 fs.writeFileSync 输出的 JSON 文件的最大大小是多少
- c# - 在回发时保持手风琴状态
- gmail - 使用 Mailkit 从谷歌下载电子邮件,因为纯/文本每 78 个(可能)字符就断行
- woocommerce - 如何在类别页面上动态显示产品类别名称
- regex - 正则表达式难以过滤结果
- javascript - 登出时服务器不可达怎么办
- python - 如何在 Python 中将问题和分数放在一起
- java - 从 firebase 数据库获取数据时,期望开始数组时出错