我如何测试一个断言? [英] How do I test an assertion?

查看:76
本文介绍了我如何测试一个断言?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我发现了如何测试异常或错误: 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:

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屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆