Flutter中如何使用Matcher测试不相等?渲染对象测试求助
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
notEqualdoesn't exist in Flutter's test matchers—there's no built-in matcher with that name.- Using
!equals(...)doesn't work becauseequalsreturns aMatcherobject, 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.isNotis designed specifically to invert matcher outcomes.
内容的提问来源于stack exchange,提问作者Suragch

