Skip to content

Instantly share code, notes, and snippets.

@smat
Created October 14, 2011 08:42
Show Gist options
  • Save smat/1286584 to your computer and use it in GitHub Desktop.
Save smat/1286584 to your computer and use it in GitHub Desktop.
ResultSetMock
import org.apache.commons.lang.NotImplementedException;
import org.apache.commons.lang.StringUtils;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.ResultSet;
import java.util.HashMap;
public class ResultSetMock {
private HashMap<String, Object> columnName;
private HashMap<Integer,Object> columnId;
private int id;
public ResultSetMock() {
columnName = new HashMap<String, Object>();
columnId = new HashMap<Integer, Object>();
id = 1;
}
public static ResultSetMock.Builder createResultSetMockBuilder() {
return new ResultSetMock().new Builder();
}
public class Builder {
public Builder addResult(String key, Object value) {
columnName.put(key, value);
columnId.put(id, value);
id++;
return this;
}
public ResultSet build() {
ResultSetInvocationHandler handler = ResultSetMock.this.new ResultSetInvocationHandler();
Class<?>[] classes = {ResultSet.class};
return (ResultSet) Proxy.newProxyInstance(ResultSetMock.class.getClassLoader(), classes, handler);
}
}
private class ResultSetInvocationHandler implements InvocationHandler {
public Object invoke(Object o, Method method, Object[] objects) throws Throwable {
if (StringUtils.startsWith(method.getName(), "get")) {
if (objects.length > 0 && objects[0] instanceof Integer) {
return columnId.get((Integer) objects[0]);
}
else if (objects.length > 0 && objects[0] instanceof String) {
return columnName.get((String) objects[0]);
}
}
throw new NotImplementedException();
}
}
}
import org.junit.Test;
import java.sql.ResultSet;
public class Usage {
@Test
public void test() {
ResultSet resultSetMock = ResultSetMock.createResultSetMockBuilder()
.addResult("COLUMN1", "somevalue")
.addResult("COLUMN2", 1)
.build();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment