Suragch
Suragch

Reputation: 512426

How to test not equal with matcher in flutter

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:

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

Upvotes: 50

Views: 26788

Answers (2)

Chuck Batson
Chuck Batson

Reputation: 2774

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));
});

Upvotes: 5

Suragch
Suragch

Reputation: 512426

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.

Upvotes: 100

Related Questions