我正在为 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)
如测试代码中所述,acceptURL 方法没有被DriverManager
. 有什么我想念的想法吗?