我如何测试一个断言? [英] How do I test an assertion?
问题描述
我发现了如何测试异常或错误: https://stackoverflow.com/a/54241438/6509751
但是我如何测试以下 assert
是否正常工作?
void notBeNull(dynamic param){
assert(param!= null);
}
我尝试了以下操作,但不起作用。断言只是简单地打印出来,测试失败:
void main(){
测试('cannoBeNull断言',(){
Expect(cannotBeNull(null),throwsA(const TypeMatcher< AssertionError>()));
});
}
有两个关键方面
-
使用
throwAssertionError
。
示例:
expect((){
assert(false);
},throwsAssertionError);
应用于问题中的代码:
<前置类= lang-dart prettyprint-override>
void main(){
test('cannoBeNull assertion',(){
Expect(()=> cannotBeNull( null),throwsAssertionError);
});
}
为什么我们需要通过回调?好吧,如果您有一个没有参数的函数,也可以向该函数传递一个 reference 。
如果没有回调,则断言将在执行期望
之前进行评估,并且期望
无法捕获错误。通过传递回调,我们允许 expect
调用该回调,这使它可以捕获 AssertionError
并且它能够来处理它。
I found out how you can test an exception or error: https://stackoverflow.com/a/54241438/6509751
But how do I test that the following assert
works correctly?
void cannotBeNull(dynamic param) {
assert(param != null);
}
I tried the following, but it does not work. The assertion is simply printed out and the test fails:
void main() {
test('cannoBeNull assertion', () {
expect(cannotBeNull(null), throwsA(const TypeMatcher<AssertionError>()));
});
}
There are two key aspects to this:
Pass a callback to
expect
. When you do that, you can never do something wrong, even if you just instantiate an object. This was already shown in the linked answer.Use
throwAssertionError
.
Example:
expect(() {
assert(false);
}, throwsAssertionError);
Applied to the code from the question:
void main() {
test('cannoBeNull assertion', () {
expect(() => cannotBeNull(null), throwsAssertionError);
});
}
Why do we need to pass a callback? Well, if you have a function without parameters, you can also pass a reference to that as well.
If there was no callback, the assertion would be evaluated before expect
is executed and there would be no way for expect
to catch the error. By passing a callback, we allow expect
to call that callback, which allows it to catch the AssertionError
and it is able to handle it.
这篇关于我如何测试一个断言?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!