Assertions in Dart and Flutter tests: type and error matchers

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

  • type matchers,
  • error matchers.

In this series:

Type matchers

isA

The isA<T> matcher helps verifying a variable type:

test('expect: isA ❌', () {
final result = 0;
expect(result, isA<Result>());
});

This test fails with the following output:

Expected: <Instance of 'Result'>
Actual: <0>

Predefined type matchers

There is a couple of more focused type matchers: isList and isMap. These tests pass:

test('expect: isList βœ…', () {
final result = [0];
expect(result, isList);
});
test('expect: isMap βœ…', () {
final result = {0: Result(0)};
expect(result, isMap);
});

Custom type matcher

It is very easy to create your own focused type matcher using TypeMatcher class:

const isResult = TypeMatcher<Result>();

That’s it, now it can be used in tests:

test('expect: isResult βœ…', () {
final result = Result(0);
expect(result, isResult);
});

Error matchers

Error type matchers

Error type matchers are based on the TypeMatcher class from the example above, as they check for the error type: isArgumentError, isException, isNoSuchMethodError, isUnimplementedError, etc.

test('expect: isUnimplementedError βœ…', () {
final result = UnimplementedError();
expect(result, isUnimplementedError);
});

throwsA

throwsA is a matcher that ensures the method call resulted in an error. If the method call is supposed to throw, it’s unsafe to call it in the test body. Instead, it should be called inside the expect() call. throwsA matcher accepts another matcher that validates the error, for example, one of the error matchers above:

test('expect: throwsA βœ…', () {
final result = (int value) => (value as dynamic).length;
expect(() => result(0), throwsA(isNoSuchMethodError));
});

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