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:
- expect and matcher
- equality matchers
- type and error matchers
- collection matchers
- numeric and comparable matchers
- universal and custom matchers
- matcher operators
- asynchronous expect and matchers
- Flutter widget matchers
- accessibility matchers
- golden matchers
- mock invocations and parameters
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!