How to programmatically create a Java ResultSet from custom data with no database

后端 未结 7 1921
渐次进展
渐次进展 2020-12-17 08:53

I have some existing code that accepts a java.sql.ResultSet that contains info retrieved from an Oracle database. I would now like to reuse this code, but I\'d

7条回答
  •  鱼传尺愫
    2020-12-17 09:25

    This is a slightly left-field solution, but you could make use of a mocking framework (e.g. JMock). These frameworks are generally intended for creating mock implementations of interfaces for unit testing, but I see no reason why you could use one to create a "partial implementation" of java.sql.ResultSet.

    For example, say you only wanted to implement the getString() method, and nothing else:

    Mockery mockery = new Mockery();
    final ResultSet resultSet = mockery.mock(ResultSet.class);
    
    mockery.checking(new Expectations() {{
        allowing(resultSet).getString(1); will(returnValue("my first string"));
        allowing(resultSet).getString(2); will(returnValue("my second string"));
    }});
    
    // resultSet is now a java.sql.ResultSet object, which you can pass to your legacy code
    resultSet.getString(1);
    

    Rather unorthodox, and quite cumbersome, but it should work

提交回复
热议问题