Assertions in Dart and Flutter tests: matcher operators

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

  • matcher operators.

In this series:

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!

--

--

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

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