How to stub/mock JDBC ResultSet to work both with Java 5 and 6?

你离开我真会死。 提交于 2019-11-30 20:01:22

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...
}

(stub class in StubResultSetContents). If somebody has some other ideas, feel free to answer =)

I had the same problem and solved it using a Proxy implementation. It seems like it's working pretty good.

public class TestResultSet implements InvocationHandler {
    public static ResultSet createProxy(HashMap<Object, Object>[] rows) {
        return (ResultSet) Proxy.newProxyInstance(ResultSet.class.getClassLoader(),
                                             new Class[] { ResultSet.class },
                                             new TestResultSet(rows));
    }

    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
        // Find the equivalent method in the proxy class.
        Method m = TestResultSet.class.getMethod(method.getName(), method.getParameterTypes());
        if(m == null) {
            throw new SQLException("Unsupported method " + method.getName());
        }

        return m.invoke(this, args);
    }

    // Method implementations follow here (only one supplied as an example)

    public boolean isFirst() throws SQLException {
        return index ==0;
    }

}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!