检查是否有异常

编程入门 行业动态 更新时间:2024-10-17 13:37:16
本文介绍了检查是否有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

使用MiniTest规范,我可以测试代码是否引发特定异常,如下所示:

Using MiniTest spec, I can test that code raises a specific exception as follows:

proc { foo.do_bar }.must_raise SomeException

但是,我不在乎特定的异常是什么,我只想验证是否抛出了 some 异常.如果我或其他开发人员决定更改Foo#do_bar引发的异常,则只要对预期的异常进行了足够的通用指定,我的测试就不必更改.

But, I don't care what the specific exception is, I just want to verify that some exception is thrown. If I, or another developer, decides to change what exception is thrown by Foo#do_bar, my test wouldn't have to change if the expected exception was specified generally enough.

也就是说,我想这样编写测试(Exception是SomeException类的祖先):

That is, I would like to write the test this way (Exception is an ancestor of class SomeException):

proc { foo.do_bar }.must_raise Exception

这样在我运行测试时会导致失败:

By this results in a failure when I run the test:

[Exception] exception expected, not Class: <SomeException>

我可以针对异常情况更一般地编写我的Minitest规范吗?

Can I write my Minitest spec more generically with regards to exceptions?

(我要检查任何异常而不是特定异常的实际原因是,我正在使用第三方Gem,并且是引发异常的代码.实际上,我的方法A被调用了A引发了MyException,但是B捕获了该异常,然后重新引发了另一个异常,该异常与我的异常具有相同的消息[并且该消息是我应该在测试中验证的东西],但是A不同的班级.)

(The actual reason I want to check for any exception, rather than a specific exception, is that I'm using a third party Gem, and it is that code that raises the exception. In fact, my method A gets called by third party method B. A raises MyException, however B catches that exception, and re-raises a different exception. This exception has the same message as my exception [and this message is something I ought to verify in the test], but a different class.)

推荐答案

describe 'testing' do it 'must raise' do a = Proc.new {oo.non_existant} begin a[] rescue => e end e.must_be_kind_of Exception end end

无论如何,这应该非常接近您的要求.

Regardless, this should do pretty close to what you are asking for.

更多推荐

检查是否有异常

本文发布于:2023-05-28 06:57:09,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/315147.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!