使用RSpec-mock在JRuby中模拟Java接口

时间:2014-11-24 04:23:03

标签: rspec interface mocking jruby rspec-mocks

我正在为JRuby中的JDBC编写一个简单的包装器。本质上我想要一个包装类DBW,它接受​​一个连接字符串和一个可选的初始化块。

require 'java'

class DBW
    def initialize (connection_string, &optional_init_block)
        if optional_init_block
            yield
        end

        @connection_string = connection_string
    end
    def get_connection
        Java::java.sql.DriverManager.getConnection(@connection_string)
    end
end

但是在我的测试中,我想使用一个测试双作为Driver注册DriverManager,所以我在RSpec测试中完成了以下内容:

it "can produce a connection using the connection string" do 

    mock_conn = instance_double("Connection") # A dummy connection instance
    mock_driver = instance_double("Driver")
    allow(mock_driver).to receive(:acceptsURL).with(any_args) {
        # this doesn't get called when the wrapper calls getConnection on the DriverManager 
        true
    }
    # Expecting that connect would be called on the driver with the connecion string...
    allow(mock_driver).to receive(:connect).with(any_args).and_return(mock_conn)

    wrapper = DBW.new "jdbc:subprotocol:subname" do 
        # Initialize the DriverManager with the mock driver
        Java::java.sql.DriverManager.registerDriver(mock_driver)
    end

    # This should call in to DriverManager.getConnection
    conn = wrapper.get_connection
    expect(conn).to eq(mock_conn)

end

运行测试时出现以下错误:

Failures:

  1) DBW can produce a connection using the connection string
     Failure/Error: Unable to find matching line from backtrace
     Java::JavaSql::SQLException:
       No suitable driver found for jdbc:subprotocol:subname
     # java.sql.DriverManager.getConnection(java/sql/DriverManager.java:689)
     # java.sql.DriverManager.getConnection(java/sql/DriverManager.java:270)
     # java.lang.reflect.Method.invoke(java/lang/reflect/Method.java:497)
     # RUBY.get_connection(/playground/dbw.rb:12)
     # RUBY.(root)(/playground/specs/dbw_spec.rb:39)

如测试代码中所述,DriverManager未调用acceptsURL方法。我缺少什么想法?

1 个答案:

答案 0 :(得分:1)

您很可能会遇到似乎与您混淆的java.sql.DriverManager内部。如果你查看.java源代码,你会在调用者的加载器上获得连接时看到那里的检查(在调用connect之前 - acceptsURL与此无关) 。这可能是在JRuby中爆炸的东西,你可以验证java.sql.Driver生成的实例在那里但是在使用API​​时没有返回:

java.sql.DriverManager.class_eval do
  field_reader :registeredDrivers
end

# ...

Java::java.sql.DriverManager.registerDriver(mock_driver)

puts java.sql.DriverManager.registeredDrivers.to_s # returns the mock_driver (last)
# [driver[className=sun.jdbc.odbc.JdbcOdbcDriver@55974e79], driver[className=org.jruby.gen.InterfaceImpl1708146542@b02cbee]]
puts java.sql.DriverManager.getDrivers.to_a.inspect  # does not return the mock_driver
# [#<Java::SunJdbcOdbc::JdbcOdbcDriver:0x55974e79>]

我建议您将代码重构为DriverManager太多......或者只是尝试使用&#34;真实&#34; (Java)模拟驱动程序编译成.jar添加到类路径