首页 > 解决方案 > 与 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])>

我究竟做错了什么?两个列表是相同的,并且都具有相等的元素。

标签: flutterflutter-testdartz

解决方案


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'])));

推荐阅读