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

前端 未结 2 598
孤城傲影
孤城傲影 2021-01-05 07:26

I\'m testing some of my classes working with JDBC statements etc and now I got problem with JDBC ResultSet interface:

The software should run both with Java 5 and Ja

2条回答
  •  隐瞒了意图╮
    2021-01-05 07:57

    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[] 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;
        }
    
    }
    

提交回复
热议问题