检查是否有异常 [英] Checking for any exception

查看:75
本文介绍了检查是否有异常的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

使用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.

这篇关于检查是否有异常的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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