这篇文章展示了如何使用Mockito模拟java.sql.ResultSet
。 它可用于帮助单元测试代码对ResultSet
(例如ResultSetExtractor
)执行操作,而无需依赖外部数据源。
您可以通过提供列名列表和2D数据数组来创建MockResultSet
。 例如:
var rs = MockResultSet.create(new String[] { "name", "age" }, //columnsnew Object[][] { // data{ "Alice", 20 },{ "Bob", 35 },{ "Charles", 50 }});
MockResultSet
的代码如下所示(也可以在我的GitHub Repository中找到 )。 请注意,我仅模拟了诸如next
, getString
和getObject
类的一些方法,但是通过遵循相同的模式来模拟其余方法非常容易。
public class MockResultSet {private final Map<String, Integer> columnIndices;private final Object[][] data;private int rowIndex;private MockResultSet(final String[] columnNames,final Object[][] data) {// create a map of column name to column indexthis.columnIndices = IntStream.range(0, columnNames.length).boxed().collect(Collectors.toMap(k -> columnNames[k],Function.identity(),(a, b) ->{ throw new RuntimeException("Duplicate column " + a); },LinkedHashMap::new));this.data = data;this.rowIndex = -1;}private ResultSet buildMock() throws SQLException {final var rs = mock(ResultSet.class);// mock rs.next()doAnswer(invocation -> {rowIndex++;return rowIndex < data.length;}).when(rs).next();// mock rs.getString(columnName)doAnswer(invocation -> {final var columnName = invocation.getArgumentAt(0, String.class);final var columnIndex = columnIndices.get(columnName);return (String) data[rowIndex][columnIndex];}).when(rs).getString(anyString());// mock rs.getObject(columnIndex)doAnswer(invocation -> {final var index = invocation.getArgumentAt(0, Integer.class);return data[rowIndex][index - 1];}).when(rs).getObject(anyInt());final var rsmd = mock(ResultSetMetaData.class);// mock rsmd.getColumnCount()doReturn(columnIndices.size()).when(rsmd).getColumnCount();// mock rs.getMetaData()doReturn(rsmd).when(rs).getMetaData();return rs;}/*** Creates the mock ResultSet.** @param columnNames the names of the columns* @param data* @return a mocked ResultSet* @throws SQLException*/public static ResultSet create(final String[] columnNames,final Object[][] data)throws SQLException {return new MockResultSet(columnNames, data).buildMock();}
}
翻译自: https://www.javacodegeeks.com/2018/09/java-mocking-resultset-using-mockito.html