如何使用Java 5和6来存根/模拟JDBC ResultSet? [英] How to stub/mock JDBC ResultSet to work both with Java 5 and 6?
问题描述
我正在测试一些使用JDBC语句等的类,现在我遇到了JDBC ResultSet接口的问题:
I'm testing some of my classes working with JDBC statements etc and now I got problem with JDBC ResultSet interface:
软件应该同时运行Java 5和Java 6以及测试也应该与两个版本一起运行。不幸的是,Java 6引入了一堆新方法(这仍然不是什么大问题),它们返回了一堆新的类/接口,这使得事情变得更加困难。 (参见 Frank Carver的Punch Barrel - Java 6打破JDBC 例如)
The software should run both with Java 5 and Java 6 and hence the tests should also be run with both versions. Unfortunately Java 6 has introduced a bunch of new methods (which is still not a big deal) that return a bunch of new classes/interfaces, which makes the things more difficult. (see Frank Carver’s Punch Barrel - Java 6 breaks JDBC for example)
在找出这些版本差异之前,我考虑了在存根和模拟之间并最终使用存根,因为ResultSet具有内部状态(当前行处理),即我更自然地使用存根,因为:
Before finding out these version differences, I considered between stubbing and mocking and ended up with stubbing because the ResultSet has internal state (current row handled) that is more natural to me to work with stubs, as :
public class StubResultSet implements ResultSet {
private Object[][] data;
private int currentRow = -1;
private boolean closed = false;
public StubResultSet(Object[][] data) {
this.data = data;
}
public Object getObject(int columnIndex) throws SQLException {
checkClosed();
return data[currentRow][columnIndex];
}
public String getString(int columnIndex) throws SQLException {
checkClosed();
return (String) getObject(columnIndex);
}
// ...
}
<但是如果我没有将新方法作为公共NClob getNClob(int columnIndex)
引入,那么这个类在Java 6下被破坏了 - 如果我把它们介绍给破解的类在Java 5下。
But if I don't introduce the new methods as public NClob getNClob(int columnIndex)
, the class is broken under Java 6 - if I introduce them the class in broken under Java 5.
我可以使用mockito(例如)回调来使状态反映返回值,但是有人有其他的 - 也许更好 - 想法?
I can work with mockito (for example) callbacks to have the state being reflected with the return values but does somebody have some other - maybe more nice - idea?
推荐答案
好吧,经过一番思考后,我最终得到了存根类并用 Mockito as:
Well, after some thinking I ended up having the stub class as there and mocking it with Mockito as:
public static ResultSet initMock(Object[][] data) throws SQLException {
final StubResultSetContents contents = new StubResultSetContents(data);
ResultSet rs = mock(ResultSet.class, RETURNS_SMART_NULLS);
when(rs.getObject(anyInt())).thenAnswer(new Answer<Object>() {
public Object answer(InvocationOnMock invocation) throws Throwable {
return contents.getObject(getIntArgument(invocation));
}
});
// a bunch of similar when(...).thenAnswer(...) constructs...
}
(StubResultSetContents中的存根类)。如果有人有其他想法,请随时回答=)
(stub class in StubResultSetContents). If somebody has some other ideas, feel free to answer =)
这篇关于如何使用Java 5和6来存根/模拟JDBC ResultSet?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!