データベースから情報を取得するために使用されるいくつかの DAO オブジェクトがあり、それらの自動テストを作成したいと思っていますが、その方法を理解するのに苦労しています。
Spring を使用して(準備済みステートメントを介して) 実際のクエリを実行し、結果を (クラスJdbcTemplate
を介して) モデル オブジェクトにマップしています。RowMapper
単体テストを作成する場合、オブジェクトをどのようにモックするか、またはモックする必要があるかわかりません。たとえば、読み取りしかないため、jdbcTemplate をモックするのではなく、実際のデータベース接続を使用しますが、それが正しいかどうかはわかりません。
バッチの最も単純な DAO の (簡略化された) コードは次のとおりです。
/**
* Implementation of the {@link BusinessSegmentDAO} interface using JDBC.
*/
public class GPLBusinessSegmentDAO implements BusinessSegmentDAO {
private JdbcTemplate jdbcTemplate;
private static class BusinessSegmentRowMapper implements RowMapper<BusinessSegment> {
public BusinessSegment mapRow(ResultSet rs, int arg1) throws SQLException {
try {
return new BusinessSegment(rs.getString(...));
} catch (SQLException e) {
return null;
}
}
}
private static class GetBusinessSegmentsPreparedStatementCreator
implements PreparedStatementCreator {
private String region, cc, ll;
private int regionId;
private GetBusinessSegmentsPreparedStatementCreator(String cc, String ll) {
this.cc = cc;
this.ll = ll;
}
public PreparedStatement createPreparedStatement(Connection connection)
throws SQLException {
String sql = "SELECT ...";
PreparedStatement ps = connection.prepareStatement(sql);
ps.setString(1, cc);
ps.setString(2, ll);
return ps;
}
}
public GPLBusinessSegmentDAO(DataSource dataSource) {
jdbcTemplate = new JdbcTemplate(dataSource);
}
public Collection<BusinessSegment> getBusinessSegments(String cc, String ll) {
return jdbcTemplate.query(
new GetBusinessSegmentsPreparedStatementCreator(cc, ll),
new BusinessSegmentRowMapper());
}
}
任意のアイデアをいただければ幸いです。
ありがとう!