[英]How to test if method that takes argument is throwing an exception in dart?
如果我有
class ErrorThrower{
void throwAnError(String argument){
throw new Error();
}
}
我想测试throwAnError是否抛出Exception,或者更确切地说是Error
的实例
这是我的代码,但它不起作用
test('', () {
var errorThrower = new ErrorThrower();
expect(errorThrower.throwAnError("string"), throwsException);
});
Dart的测试包可以检测抛出的错误,但该函数要么是异步的(最常见的是返回Future
),要么作为回调提供,因此expect
函数可以懒惰地评估它。 在你的例子中:
test('', () {
var errorThrower = new ErrorThrower();
expect() => errorThrower.throwAnError("string"), throwsError);
});
... 应该管用。 请注意,我写了throwsError
而不是throwsException
,在Dart中这些是两个不同的东西(不相互继承),意图是错误不是故意在生产代码中捕获,而是异常(例如FormatException
)应该是。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.