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

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!

--

--

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

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