use_test_throws_matchers
使用 throwsA 匹配器代替 fail()。
详情
#使用 throwsA
匹配器代替 try-catch 结构和 fail()
。
错误示例
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'));
}
正确示例
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'))),
);
启用
#要启用 use_test_throws_matchers
规则,请在您的 analysis_options.yaml
文件中的 linter > rules 下添加 use_test_throws_matchers
analysis_options.yaml
yaml
linter:
rules:
- use_test_throws_matchers
如果您使用 YAML 映射语法来配置 linter 规则,请在 linter > rules 下添加 use_test_throws_matchers: true
analysis_options.yaml
yaml
linter:
rules:
use_test_throws_matchers: true
除非另有说明,否则本网站上的文档反映了 Dart 3.7.1 版本。页面上次更新于 2025-03-07。 查看源代码 或 报告问题。