Answer the question
In order to leave comments, you need to log in
How to test DAO layer in Java with Mockito?
Good day. Could you give an example of testing a DAO layer using mock objects? Or advise a resource where you can read about it.
If you point out errors in the code, I will only be grateful)
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;
}
}
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question