内容

use_test_throws_matchers

使用 throwsA 匹配器代替 fail()。

此规则从 Dart 2.14 开始可用。

详情

#

使用throwsA匹配器代替带有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