Assertions in Dart and Flutter tests: expect and matcher
This is the part of the ultimate cheat sheet dedicated to:
- asserting with
expect()
, - matcher.
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
Expect
expect()
is the main assertion function. Letβs take a look at this test:
test('expect: value β
', () {
final result = 0;
expect(result, 0);
});
where result
is a value that would typically come from software under test.
Here, expect()
ensures that the result
is 0
. If it is different, it will throw the TestFailure
exception, leading to the test failure.
Additionally, expect()
prints the description of the problem to the output. For example, for this test:
test('expect: value β', () {
final result = 1;
expect(result, 0);
});
weβll see the following output:
Expected: <0>
Actual: <1>
Here is the full signature of the expect()
method:
void expect(
dynamic actual, // actual value to be verified
dynamic matcher, { // characterises the expected result
String? reason, // added to the output in case of failure
dynamic skip, // true or a String with the reason to skip
}) {...}
expect()
accepts an optional reason
that can be added to the output. For this test:
test('expect: reason β', () {
final result = 1;
expect(result, 0, reason: 'Result should be 0!');
});
the output is:
Expected: <0>
Actual: <1>
Result should be 0!
expect()
also accepts an optional skip
that can be either true
or a String
:
test('expect: skip β
', () {
final result = 1;
expect(result, 0, skip: true);
expect(result, 0, skip: 'for a reason');
});
This test succeeds with the following output:
Skip expect (<0>).
Skip expect: for a reason
Attention! The usage of the skip
parameter does not skip the entire test, but only the expect()
call it is applied to.
Matcher
Matcher is an instance that validates that the value satisfies some expectation based on the matcher type. It is either a child of the Matcher
base class or a value. Matcher is also responsible for providing a meaningful description of a mismatch in case of test failure.
Check other parts of the series to learn about the variety of available matchers.
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!