I am testing a simple DAO layer with mockito, but I found the problem, basically a tough interface to test, and I was wondering if you can give me some idea ...
This is the method I want to check:
public Person getById(UserId id) {
final Person person = new PersonImpl();
gateway.executeQuery(GET_SQL + id.getUserId(), new ResultSetCommand(){
public int work(ResultSet rs) throws SQLException {
if(rs.next()){
person.getName().setGivenName(rs.getString("name"));
person.getName().setFamilyName(rs.getString("last_name"));
}
return 0;
}
});
return person;
}
I use DatabaseGateway, which is my interface between Java code and SQL, and this method accepts an anonymous class, this is the executeQuery method of the gateway:
public int executeQuery(String sql, ResultSetCommand cmd) {
try{
Connection cn = createConnection();
PreparedStatement st = cn.prepareStatement(sql);
int result = cmd.work(st.executeQuery());
cn.close();
return result;
}catch(Exception e){
throw new RuntimeException("Cannot Create Statement for sql " + sql,e);
}
}
The fact is that because of this anonymous class, it becomes harder for him to test PersonDAO.
I can reorganize all the code, even delete an anonymous class, if someone offers a better design (I'm sure there is simpler, but I just can not find it).
Thanks everyone for the suggestions.
PD: if you need more information, feel free to ask
: ,
public void testGetPersonById(){
DatabaseGateway gateway = mock(DatabaseGateway.class);
when(gateway.executeQuery(anyString(),any(ResultSetCommand.class)));
PersonDAO person_dao = new PersonDAOImpl(gateway);
Person p = person_dao.getById(new UserId(Type.viewer,"100"));
}
? ResultCommand , ... ?