ruby - JRuby 和 Test::Unit 的 assert_raise

标签 ruby unit-testing jruby assert testunit

我无法让 assert_raise 识别 java 异常。

我可以

assert_raise(NativeException) { @iter.next }

效果很好,但如果我尝试更具体一些

java_import 'java.util.NoSuchElementException'
#...
assert_raise(NoSuchElementException) { @iter.next }

我得到了错误

Should expect a class of exception, Java::JavaUtil::NoSuchElementException.
<nil> is not true.

但是,我可以使用 begin/rescue/end 来捕获异常:

assert(begin
         @iter.next
         false
       rescue NoSuchElementException
         true
       end)

是我做错了什么,还是 Test::Unit 部分失败了?

最佳答案

我会把它作为一个错误提出来。它似乎无法理解在 block 中引发的 java 类,因为它返回 nil,因此未通过测试。

我在 jruby 1.4.0 (ruby 1.8.7 patchlevel 174) (2009-11-02 69fbfa3) (Java HotSpot(TM) Client VM 1.5.0_22) [i386-java] 下运行它

include Java
import java.util.NoSuchElementException
require 'test/unit'

class FooBar < Test::Unit::TestCase
  def test_foo
    exception_caught = false
    begin
      raise NoSuchElementException.new("Bad param")
    rescue NoSuchElementException => e
     exception_caught = true
    end
   assert exception_caught
 end

  def test_bar
    assert_raise NoSuchElementException do
      raise NoSuchElementException.new("Bad param")
    end
  end
end

关于ruby - JRuby 和 Test::Unit 的 assert_raise,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2187166/

相关文章:

c - Ruby 方法的大 O 符号?

数组中的 Ruby map 方法

ruby - 使2个数组大小相同

c++ - 系统编程中的单元测试?

java - 验证方法体中是否使用了方法参数

ruby rake with rails 在生产中缺少常量,但在开发环境中工作

ruby - 从字符串数组创建对象数组

Ruby - 相同类类型的常量

javascript - 如何在 Jasmine 中假装离线?

java - 从 jruby 和 warbled jar 运行之间有什么区别 "under the hood"?