samedi 7 février 2015

How to test DAO methods using Mockito?

I've started to discovered Mockito library and there is a question for which I didn't find the proper answer.


If I have for example such method in my UserDAO class that saves user in database:



public class UserDAO{
...
public void create(User user) {
Connection connection = null;
PreparedStatement pstmt = null;
ResultSet generatedKeys = null;
try {

connection = getConnection();
pstmt = connection.prepareStatement(INSERT_USER,
PreparedStatement.RETURN_GENERATED_KEYS);
int counter = 1;
pstmt.setString(counter++, user.getFirstName());
pstmt.setString(counter++, user.getLastName());
pstmt.setString(counter++, user.getEmail());
pstmt.setString(counter++, user.getPassword());
pstmt.setString(counter, user.getRole());
pstmt.setString(counter, user.getLang());

pstmt.execute();
connection.commit();
generatedKeys = pstmt.getGeneratedKeys();

if (generatedKeys.next()) {
user.setId(generatedKeys.getInt(Fields.GENERATED_KEY));
}
} catch (SQLException e) {
rollback(connection);
LOG.error("Can not create a user", e);
} finally {
close(connection);
close(pstmt);
close(generatedKeys);
}
}
....
}


How should I test it ?


If I want to test for example a DAO class then I need to create a DataSource mock, Connection mock, ResultSet mock etc ? And so not to test the database itself ?


But what if I want to also test the behavior of dao and database ?


Would you please prodce some code samples, links that could be helpful.


Aucun commentaire:

Enregistrer un commentaire