Skip to content

Instantly share code, notes, and snippets.

@schauder
Last active August 16, 2017 08:40
Show Gist options
  • Save schauder/0a8807b9c33b2d500c168db73509a545 to your computer and use it in GitHub Desktop.
Save schauder/0a8807b9c33b2d500c168db73509a545 to your computer and use it in GitHub Desktop.
Mocking a ResultSet
static ResultSet mockResultSet(List<String> columns, Object... values) {
Assert.isTrue( //
values.length % columns.size() == 0, //
String //
.format( //
"Number of values [%d] must be a multiple of the number of columns [%d]", //
values.length, //
columns.size() //
) //
);
List<Map<String, Object>> result = convertValues(columns, values);
return mock(ResultSet.class, new ResultSetAnswer(result));
}
private static List<Map<String, Object>> convertValues(List<String> columns, Object[] values) {
List<Map<String, Object>> result = new ArrayList<>();
int index = 0;
while (index < values.length) {
Map<String, Object> row = new HashMap<>();
result.add(row);
for (String column : columns) {
row.put(column, values[index]);
index++;
}
}
return result;
}
private static class ResultSetAnswer implements Answer {
private final List<Map<String, Object>> values;
private int index = -1;
public ResultSetAnswer(List<Map<String, Object>> values) {
this.values = values;
}
@Override
public Object answer(InvocationOnMock invocation) throws Throwable {
if (invocation.getMethod().getName().equals("next"))
return next();
if (invocation.getMethod().getName().equals("getObject"))
return getObject(invocation.getArgument(0));
throw new OperationNotSupportedException();
}
private Object getObject(String column) {
return values.get(index).get(column);
}
private boolean next() {
index++;
return index < values.size();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment