如何在颤振中测试与匹配器不相等

Sur*_*gch 23 testing matcher dart flutter

我正在 Flutter 中对渲染对象进行测试。我想检查这样的不平等(简化):

testWidgets('render object heights not equal', (WidgetTester tester) async {

  final renderObjectOneHeight = 10;
  final renderObjectTwoHeight = 11;

  expect(renderObjectOneHeight, notEqual(renderObjectTwoHeight));
});
Run Code Online (Sandbox Code Playgroud)

我编造了,notEqual因为它不存在。这也不起作用:

  • !equals

我找到了一个有效的解决方案,所以我在问答风格下发布了我的答案。不过,我欢迎任何更好的解决方案。

Sur*_*gch 45

您可以使用isNot()来否定equals()匹配器。

final x = 1;
final y = 2;

expect(x, isNot(equals(y)));
Run Code Online (Sandbox Code Playgroud)

或者如评论中所述:

expect(x != y, true)
Run Code Online (Sandbox Code Playgroud)

这对我来说实际上似乎更具可读性。

  • @ BambinoUA & @Suragch `expect(x, isNot(equals(y)));` 应该优于 `expect(x != y, true)` 的原因是第一个会给你实际的比较测试失败,而后者只会抱怨预期为真实际为假,这使得需要使用调试器进行第二次运行才能获得更多见解。(但我同意;D 第一个读起来更好) (4认同)
  • 为什么不只使用“expect(x != y, true)”? (2认同)