47

I'm doing testing on render objects in Flutter. I'd like to check for inequality like this (simplified):

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

  final renderObjectOneHeight = 10;
  final renderObjectTwoHeight = 11;

  expect(renderObjectOneHeight, notEqual(renderObjectTwoHeight));
});

I made up notEqual because it doesn't exist. This doesn't work either:

  • !equals

I found a solution that works so I am posting my answer below Q&A style. I welcome any better solutions, though.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393

2 Answers2

92

You can use isNot() to negate the equals() matcher.

final x = 1;
final y = 2;

expect(x, isNot(equals(y)));

Or as mentioned in the comments:

expect(x != y, true)

That actually seems a bit more readable to me.

Suragch
  • 484,302
  • 314
  • 1,365
  • 1,393
  • 1
    A lot of various matchers are documented in https://api.flutter.dev/flutter/flutter_test/flutter_test-library.html – rlat May 16 '20 at 10:42
  • 3
    Why don't use just `expect(x != y, true)`? – BambinoUA May 20 '21 at 08:12
  • @BambinoUA, Good question. – Suragch May 21 '21 at 00:45
  • 4
    @ BambinoUA & @Suragch the reason `expect(x, isNot(equals(y)));`should be preferred over `expect(x != y, true)` is that the first one will give you the actual comparison upon the test failing while the later will just complain expected true actual false which makes a second run with the debugger necessary to gain more insights. (But I agree ;D the first one reads better) – Marco Papula Nov 17 '21 at 10:00
3

Since the behavior for the matcher argument of expect(), as well as the argument to isNot(), is to treat non-function values as if wrapped in equals(), you can succinctly write the following without using equals():

expect(123, 123);
expect(123, isNot(456));

Your example would then be

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

  final renderObjectOneHeight = 10;
  final renderObjectTwoHeight = 11;

  expect(renderObjectOneHeight, isNot(renderObjectTwoHeight));
});
Chuck Batson
  • 2,165
  • 1
  • 17
  • 15