xpe*_*dev 9 dart flutter flutter-test
简而言之,throwsA(anything)用dart进行单元测试不足以满足我的需求。如何测试特定的错误消息或类型?
这是我要捕获的错误:
class MyCustErr implements Exception {
String term;
String errMsg() => 'You have already added a container with the id
$term. Duplicates are not allowed';
MyCustErr({this.term});
}
Run Code Online (Sandbox Code Playgroud)
这是当前通过的断言,但是要检查上面的错误类型:
expect(() => operations.lookupOrderDetails(), throwsA(anything));
这就是我想做的:
expect(() => operations.lookupOrderDetails(), throwsA(MyCustErr));
Ber*_*Ber 14
在 Flutter 1.12.1 中不推荐使用 `TypeMatcher<>' 之后,我发现它可以工作:
expect(() => operations.lookupOrderDetails(), throwsA(isInstanceOf<MyCustErr>()));
Run Code Online (Sandbox Code Playgroud)
截至 2021 年 4 月,这是正确的方法。
正确的方法
import 'package:dcli/dcli.dart';
import 'package:test/test.dart';
/// GOOD: works in all circumstances.
expect(() => restoreFile(file), throwsA(isA<RestoreFileException>()));
Run Code Online (Sandbox Code Playgroud)
一些例子显示:
方法不正确
import 'package:dcli/dcli.dart';
import 'package:test/test.dart';
/// BAD: works but not in all circumstances
expect(restoreFile(file), throwsA(isA<RestoreFileException>()));
Run Code Online (Sandbox Code Playgroud)
注意在期望之后缺少的 '() => '。
不同之处在于第一种方法适用于返回 void 的函数,而第二种方法则不能。
所以第一种方法应该是首选技术。
要测试特定的错误消息:
检查异常内容
import 'package:dcli/dcli.dart';
import 'package:test/test.dart';
expect(
() => copy(from, to),
throwsA(predicate((e) =>
e is CopyException &&
e.message == 'The from file ${truepath(from)} does not exists.')));
Run Code Online (Sandbox Code Playgroud)
这应该做您想要的:
expect(() => operations.lookupOrderDetails(), throwsA(const TypeMatcher<MyCustErr>()));
expect(() => operations.lookupOrderDetails(), isInstanceOf<MyCustErr>());
Run Code Online (Sandbox Code Playgroud)
如果您只想检查异常,请检查以下答案:
| 归档时间: |
|
| 查看次数: |
1533 次 |
| 最近记录: |