use_test_throws_matchers
使用 throwsA matcher 取代 fail()。
詳細資訊
#使用 throwsA
matcher 取代搭配 fail()
的 try-catch。
不良範例
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 map 語法來設定 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。 檢視原始碼 或 回報問題。