gpt4 book ai didi

java - 在 spock 中模拟 Jdbc 接口(interface)

转载 作者:行者123 更新时间:2023-11-30 10:33:05 26 4
gpt4 key购买 nike

我正在研究一个微型 framework包装名为 spwrap 的数据库存储过程调用

Here's the code :

@ConfineMetaClassChanges([CallableStatement])
def "Result of output parameter getInt throws SQLException" (){

given:
def sqlExceptionMsg = "exception happend while tring to call getInt"
CallableStatement.metaClass.getObject = { int parameterIndex -> throw new SQLException(sqlExceptionMsg)}

when:
def custId = customerDao.createCustomer("Abdullah", "Mohammad")

then:
def e = thrown(CallException)
e.cause == SQLException
e.cause.message == sqlExceptionMsg
}

方法 createCustomer 不返回对 CallableStatement 的引用, 然而在引擎盖下 CallableStatement.getObject(int)正在调用,我想测试 SQLException 的情况被抛出。

我正在尝试覆盖 CallableStatement.getObject(int) 上的 bahvaiour类(因为我必须引用框架使用的对象 - 至少在这种情况下)

上面的测试失败了,因为看起来是 CallableStatement.getObject(int)没有被改变。然而,当我使用 <<它提示(它应该)。如何实现?

更新:

使用 GroovyMock没有帮助:

// test fails!
def "Calling interface methods calling JDBC Driver methods" (){
given:
CustomerDAO customerDAO2 = new DAO.Builder("jdbc:hsqldb:mem:customers", "sa", "").build().create(CustomerDAO);
def callableStatement = GroovyMock(JDBCCallableStatement, global: true)
when:
customerDAO2.createCustomer("Abdullah", "Mohammad")
then:
1 * callableStatement.getObject(_ as Integer)
}

我可以使用其他 Mocking 框架实现这一点吗?

最佳答案

根据我的经验,Spock 在模拟静态/最终 Java 代码方面并不是很强大。我采取的一种变通方法是将任何此类方法调用放在它们自己的方法中,Spock 应该可以毫无问题地挂接进去。

public class MyClass {
//... stuff ...

protected Object retrieveObject(int) throws SQLException {
return CallableStatement.getObject(int)
}
}

public class MyClassTest extends Specification {
def "Test example for wrapping unmockable method" (){
given:
MyClass example = new MyClass();
when:
example.callMethod("Parameters")
then:
1 * example.retrieveObject(_) >> { throw new SQLException(sqlExceptionMsg) }
}
}

关于java - 在 spock 中模拟 Jdbc 接口(interface),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42372921/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com