You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Flutter中如何使用Matcher测试不相等?渲染对象测试求助

How to test if two values are NOT equal in Flutter widget tests?

I'm working on testing render objects in Flutter, and I need to verify that two height values aren't the same. I wrote this simplified test code, but it doesn't work because notEqual is a made-up method I thought might exist:

testWidgets('render object heights not equal', (WidgetTester tester) async { 
  final renderObjectOneHeight = 10; 
  final renderObjectTwoHeight = 11; 
  expect(renderObjectOneHeight, notEqual(renderObjectTwoHeight)); 
});

I also tried using !equals but that didn't get the job done either. I've figured out a working solution and wanted to share it here, plus I'd love to hear if there are better ways to do this.


My Answer

Working, Idiomatic Solution

The correct way to check for inequality in Flutter tests is to use the isNot matcher combined with equals. This inverts the equality check properly within the test framework's matcher system. Here's the fixed code:

testWidgets('render object heights not equal', (WidgetTester tester) async { 
  final renderObjectOneHeight = 10; 
  final renderObjectTwoHeight = 11; 
  expect(renderObjectOneHeight, isNot(equals(renderObjectTwoHeight))); 
});

Alternative Concise Approach

If you want a shorter (though less standard) option, you can use a predicate matcher with the != operator. This lets you define a custom check directly:

testWidgets('render object heights not equal', (WidgetTester tester) async { 
  final renderObjectOneHeight = 10; 
  final renderObjectTwoHeight = 11; 
  expect(renderObjectOneHeight, predicate((val) => val != renderObjectTwoHeight)); 
});

Why Your Initial Tries Failed

  • notEqual doesn't exist in Flutter's test matchers—there's no built-in matcher with that name.
  • Using !equals(...) doesn't work because equals returns a Matcher object, not a boolean. The ! operator tries to negate the matcher itself (which isn't a boolean), so it doesn't behave as you'd expect. isNot is designed specifically to invert matcher outcomes.

内容的提问来源于stack exchange,提问作者Suragch

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.14 08:59:00