简体   繁体   English

Mockito监视HSQLDB连接

[英]Mockito spy on a HSQLDB connection

I am writing test cases for some code that uses HSQLDB to get its data from. 我正在为一些使用HSQLDB从中获取数据的代码编写测试用例。 However, there is a certain query/function called by my DAO which isn't supported in the in-memory database. 但是,内存数据库中不支持我的DAO调用的某些查询/函数。

I am trying to return a custom ResultSet when this specific query is fired and default on the normal behavior otherwise (fetching from in memory database). 我尝试在触发此特定查询时返回自定义ResultSet ,否则将默认返回正常行为(从内存数据库中获取)。

Relevant pieces of code: 相关代码段:

db = new EmbeddedDatabaseBuilder().addScript("resources/create-test-db.sql")
    .addScript("resources/add-test-data.sql").build();
Connection conn = Mockito.spy(db.getConnection());

PreparedStatement mockPreparedStatement = Mockito.mock(PreparedStatement.class); 
when(conn.prepareStatement(query)).thenReturn(mockPreparedStatement);

And I pass on conn to my object. 然后我将conn传递给我的对象。 However, it seems HSQL is actually trying to run the query and thus, I get an error. 但是,似乎HSQL实际上正在尝试运行查询,因此,我得到了一个错误。

How should I do this? 我应该怎么做?

模拟间谍时需要使用doReturn()

doReturn(mockPreparedStatement).when(conn).prepareStatement(query);

Important gotcha on spying real objects! 从事间谍活动的重要陷阱!

Sometimes it's impossible or impractical to use when(Object) for stubbing spies. 有时,使用when(Object)来侦探间谍是不可能或不切实际的。 Therefore when using spies please consider doReturn|Answer|Throw() family of methods for stubbing. 因此,在使用间谍程序时,请考虑使用doReturn | Answer | Throw()系列方法进行存根。

Example: 例:

List list = new LinkedList();
List spy = spy(list);
//Impossible: real method is called so spy.get(0) throws IndexOutOfBoundsException (the list is yet empty)
when(spy.get(0)).thenReturn("foo");
//You have to use doReturn() for stubbing
doReturn("foo").when(spy).get(0);

Source: Mockito Documentation 资料来源: Mockito文档

So in your case, try this: 因此,请尝试以下操作:

doReturn(mockPreparedStatement).when(conn).prepareStatement(query);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM