如何使用 Mockito 测试 DAO 方法?
2022-09-01 10:49:47
						我开始发现Mockito库,有一个问题我没有找到正确的答案。
例如,如果我在我的UserDAO类中有这样的方法,它将用户保存在数据库中:
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);
        }
    }
  ....
}
我应该如何测试它?
如果我想测试例如DAO类,那么我需要创建一个模拟,模拟,模拟等?所以不测试数据库本身?DataSourceConnectionResultSet
但是,如果我也想测试dao和数据库的行为呢?
您是否可以生成一些代码示例,链接,这些链接可能会有所帮助并显示执行此操作的最佳方法?