Доброго времени суток. Не могли бы вы привести пример тестирования DAO слоя используя Mock-объекты? Или посоветуйте ресурс где можно об этом почитать.
Если укажите на ошибки в коде буду только благодарен)
DataSource
public class DataSource {
public static final Logger log = Logger.getLogger(DataSource.class);
BasicDataSource connectionPool;
public DataSource() {
Properties prop = getProperties();
log.info("Connection pool init...");
connectionPool = new BasicDataSource();
connectionPool.setUsername(prop.getProperty("db.username"));
connectionPool.setPassword(prop.getProperty("db.password"));
connectionPool.setDriverClassName("db.driver");
connectionPool.setUrl("db.url");
connectionPool.setInitialSize(1);
log.info("Connection pool ready");
}
private Properties getProperties(){
Properties properties = new Properties();
try {
InputStream in = getClass().getClassLoader().getResourceAsStream("db.properties");
properties.load(in);
return properties;
} catch (IOException e) {
log.warn("Error of reading db.properties.");
}
return properties;
}
public Connection getConnection() throws SQLException {
Connection connection = connectionPool.getConnection();
connection.setAutoCommit(false);
return connection;
}
}
Метод что требуется оттестить
public class UserDaoImpl implements UserDao {
public UserDaoImpl() {
this.dataSource = new DataSource();
}
public User findByEmail(String email) {
log.info("Search by email: " + email);
User user = null;
PreparedStatement preparedStatement = null;
ResultSet resultSet = null;
try {
Connection connection = dataSource.getConnection();
preparedStatement = connection.prepareStatement(FIND_BY_ID);
preparedStatement.setString(1,email);
resultSet = preparedStatement.executeQuery();
user = new User(resultSet);
return user;
} catch (SQLException e) {
log.warn("SQLException in findByEmail()");
} finally {
if(preparedStatement != null){
try {
preparedStatement.close();
} catch (SQLException e) {
log.warn("Prepared statement not closed");
}
}
}
return user;
}
}