use_test_throws_matchers
Use throwsA matcher instead of fail().
Details
#Use the throwsA
matcher instead of try-catch with fail()
.
BAD:
dart
// sync code
try {
someSyncFunctionThatThrows();
fail('expected Error');
} on Error catch (error) {
expect(error.message, contains('some message'));
}
// async code
try {
await someAsyncFunctionThatThrows();
fail('expected Error');
} on Error catch (error) {
expect(error.message, contains('some message'));
}
GOOD:
dart
// sync code
expect(
() => someSyncFunctionThatThrows(),
throwsA(isA<Error>().having((Error error) => error.message, 'message', contains('some message'))),
);
// async code
await expectLater(
() => someAsyncFunctionThatThrows(),
throwsA(isA<Error>().having((Error error) => error.message, 'message', contains('some message'))),
);
Enable
#To enable the use_test_throws_matchers
rule, add use_test_throws_matchers
under linter > rules in your analysis_options.yaml
file:
analysis_options.yaml
yaml
linter:
rules:
- use_test_throws_matchers
If you're instead using the YAML map syntax to configure linter rules, add use_test_throws_matchers: true
under linter > rules:
analysis_options.yaml
yaml
linter:
rules:
use_test_throws_matchers: true
Was this page's content helpful?
Thank you for your feedback!
Provide details Thank you for your feedback! Please let us know what we can do to improve.
Provide details Unless stated otherwise, the documentation on this site reflects Dart 3.8.1. Page last updated on 2025-03-07. View source or report an issue.