Assertions in Dart and Flutter tests: matcher operators
This is the part of the ultimate cheat sheet dedicated to:
- matcher operators.
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
Matcher operators
allOf
The allOf
matcher allows combining multiple matchers and ensures all of them are satisfied. It can be used with an array of matchers or with up to 7 individual matchers:
test('expect: allOf β
', () {
final result = Result(0);
expect(result, allOf(hasValue(0), isResult));
expect(result, allOf([hasValue(0), isResult]));
});
In case of failure:
test('expect: allOf β', () {
final result = Result(0);
expect(result, allOf([hasLength(1), hasValue(1)]));
});
The output prints errors from the first failed matcher:
Expected: (an object with length of <1> and an object with value property of <1>)
Actual: Result:<Result{result: 0}>
Which: has no length property
anyOf
The anyOf
matcher also accepts an array of matchers or up to 7 individual matchers and ensures at least one of them is satisfied:
test('expect: anyOf β
', () {
final result = Result(0);
expect(result, anyOf(hasLength(1), hasValue(0)));
expect(result, anyOf([hasLength(1), hasValue(0)]));
});
Even though hasLength
matcher fails, the overall test passes.
isNot
The isNot
matcher calls the inner matcher and inverts its matching result:
test('expect: isNot β
', () {
final result = 0;
expect(result, isNot(1));
expect(result, isNot(isResult));
expect(result, isNot(allOf(isResult, hasValue(0))));
});
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!