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:
- 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
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!