问题描述
考虑一个基于传递的参数执行一些异常处理的函数:
Consider a function that does some exception handling based on the arguments passed:
List range(start, stop) {
if (start >= stop) {
throw new ArgumentError("start must be less than stop");
}
// remainder of function
}
如何测试是否引发了正确类型的异常?
How do I test that the right kind of exception is raised?
推荐答案
在这种情况下,有多种方法可以测试异常.简单地测试是否引发了非特定异常:
In this case, there are various ways to test the exception. To simply test that an unspecific exception is raised:
expect(() => range(5, 5), throwsException);
测试是否引发了正确类型的异常:
to test that the right type of exception is raised:
有几个用于一般目的的预定义匹配器,例如 throwsArgumentError
、throwsRangeError
、throwsUnsupportedError
等.对于不存在预定义匹配器的类型,您可以使用 TypeMatcher
.
there are several predefined matchers for general purposes like throwsArgumentError
, throwsRangeError
, throwsUnsupportedError
, etc.. for types for which no predefined matcher exists, you can use TypeMatcher<T>
.
expect(() => range(5, 2), throwsA(TypeMatcher<IndexError>()));
确保不会引发异常:
expect(() => range(5, 10), returnsNormally);
测试异常类型和异常信息:
to test the exception type and exception message:
expect(() => range(5, 3),
throwsA(predicate((e) => e is ArgumentError && e.message == 'start must be less than stop')));
这是另一种方法:
expect(() => range(5, 3),
throwsA(allOf(isArgumentError, predicate((e) => e.message == 'start must be less than stop'))));
(感谢 Google 的 Graham Wheeler 提供的最后两个解决方案).
(Thanks to Graham Wheeler at Google for the last 2 solutions).
这篇关于你如何在 Dart 中对异常进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!