-->

检查任何异常(Checking for any exception)

2019-09-28 06:00发布

使用MINITEST规范,我可以测试代码中引发了一个特定的异常,如下所示:

proc { foo.do_bar }.must_raise SomeException

但是,我并不关心具体的异常是什么,我只是想确认一些则抛出异常。 如果我或其他开发者,决定改变什么异常是由富#do_bar扔了,我的测试不会有如果指定了预期的异常通常不足以改变。

也就是说,我想编写测试这种方式(例外是类SomeException的祖先):

proc { foo.do_bar }.must_raise Exception

通过这导致失败,当我运行测试:

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

我可以写我的MINITEST规格更一般地与问候例外?

(实际的原因,我想检查任何异常,而不是特定的例外情况是,我使用的是第三方的宝石,它是代码,引发异常。事实上,我的方法A得到由第三方叫方法B.甲引发MyException,然而乙捕捉该异常,并重新引发一个不同的异常。此异常具有相同的消息作为我的例外[和该消息是我应该在测试来验证],但不同的类。 )

Answer 1:

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

无论如何,这应该做的非常接近你所要求的。



Answer 2:

这似乎很奇怪的行为。

来源: http://bfts.rubyforge.org/minitest/MiniTest/Assertions.html#method-i-assert_raises

# File lib/minitest/unit.rb, line 337
def assert_raises *exp
  msg = "#{exp.pop}\n" if String === exp.last

  should_raise = false
  begin
    yield
    should_raise = true
  rescue MiniTest::Skip => e
    details = "#{msg}#{mu_pp(exp)} exception expected, not"

    if exp.include? MiniTest::Skip then
      return e
    else
      raise e
    end
  rescue Exception => e
    details = "#{msg}#{mu_pp(exp)} exception expected, not"
    assert(exp.any? { |ex|
             ex.instance_of?(Module) ? e.kind_of?(ex) : ex == e.class
           }, exception_details(e, details))

    return e
  end

  exp = exp.first if exp.size == 1
  flunk "#{msg}#{mu_pp(exp)} expected but nothing was raised." if
    should_raise
end

这将检查传来的例外就是一个实例Module ,如果是使用e.kind_of?(ex)这将很好地工作作为为实例SomeException将是一种Exception ,但只有当ex是一个模块,所以Exception将无法正常工作。 它需要共同您已经混合成你的异常的东西。

(如这里所示http://ruby-doc.org/core-2.0/Object.html#method-i-kind_of-3F )

这符合minitests自己的测试...

  module MyModule; end
  class AnError < StandardError; include MyModule; end

  ....

  def test_assert_raises
    @tc.assert_raises RuntimeError do
      raise "blah"
    end
  end

  def test_assert_raises_module
    @tc.assert_raises MyModule do
      raise AnError
    end
  end

(来源: https://github.com/seattlerb/minitest/blob/master/test/minitest/test_minitest_unit.rb )

所以..如果你的异常模块中混合,就可以断言模块上..但比其他一起去@ VGOFF的答案..或延长MINITEST做你想做什么。

注:我爱红宝石是所有开源!



文章来源: Checking for any exception
标签: ruby minitest