Assertions in Dart and Flutter tests: numeric and comparable matchers

This is the part of the ultimate cheat sheet dedicated to:

  • numeric matchers,
  • comparable matchers.

In this series:

Numeric matchers

Zero-oriented matchers

isZero, isNonZero, isPositive, isNonPositive, isNegative, isNonNegative matchers all check how the actual value is related to 0:

test('expect: isZero βœ…', () {
final result = 0;
expect(result, isZero);
});
test('expect: isPositive βœ…', () {
final result = 1;
expect(result, isPositive);
});

Range matchers

inInclusiveRange, inExclusiveRange matchers check if the actual num value is in the range:

test('expect: inInclusiveRange βœ…', () {
final result = 1;
expect(result, inInclusiveRange(0, 1));
});
test('expect: inExclusiveRange ❌', () {
final result = 1;
expect(result, inExclusiveRange(0, 1));
});

Comparable matchers

Matchers greaterThan, greaterThanOrEqualTo, lessThan, lessThanOrEqualTo use operator ==, operator <, and operator > to compare expected and actual values:

test('expect: greaterThan βœ…', () {
final result = 1;
expect(result, greaterThan(0));
});
test('expect: lessThanOrEqualTo βœ…', () {
final result = 1;
expect(result, lessThanOrEqualTo(1));
});

They can be applied not only to numeric values, but also to custom classes. To use them with our Result class, it has to be improved with operator < and operator > implementations:

class Result {
const Result(this.value);

final int value;

...

@override
bool operator ==(Object other) =>
identical(this, other) ||
other is Result &&
runtimeType == other.runtimeType &&
value == other.value;

bool operator >(Object other) =>
other is Result &&
value > other.value;

bool operator <(Object other) =>
other is Result &&
value < other.value;
}

As you see, I am comparing Result objects by the inner value field. Now, these tests also pass:

test('expect: greaterThan βœ…', () {
final result = Result(1);
expect(result, greaterThan(Result(0)));
});
test('expect: lessThanOrEqualTo βœ…', () {
final result = Result(1);
expect(result, lessThanOrEqualTo(Result(1)));
});

Originally published at Invertase blog. Check out their awesome Authors Program!

Hi! πŸ‘‹πŸ» I’m Anna, Google Developer Expert in Flutter from Ukraine πŸ‡ΊπŸ‡¦ Follow me on Twitter, GitHub, YouTube, Medium to get notifications about my latest work.

It’s early 2023, and we in Ukraine are still fighting against russians committing genocide on our lands. If you find this content useful and have a coin to spare, support us with your donations. Stand with Ukraine!

--

--

Anna Leushchenko πŸ‘©β€πŸ’»πŸ’™πŸ“±πŸ‡ΊπŸ‡¦

Google Developer Expert in Dart and Flutter | Author, speaker at tech events, mentor, OSS contributor | Passionate mobile apps creator