我想使用 Mockito(如果需要,还可以使用 PowerMockito)测试我的 DAO 方法,但我不知道该怎么做。调用静态方法的最大问题(MySQLStationDAO 中的 MySQLDAOFactory.getConnection())。你能帮助我吗?
我通过这种方式获得连接:
public class MySQLDAOFactory extends DAOFactory {
public static Connection getConnection() throws DAOException {
Connection con = null;
try {
con = getDataSource().getConnection();
} catch (SQLException e) {
throw new DAOException(Messages.CANNOT_OBTAIN_CONNECTION, e);
}
return con;
}
这是一个DAO方法:
public class MySQLStationDAO implements StationDAO {
@Override
public List<Station> getAllStations() throws DAOException {
List<Station> stations = new ArrayList<>();
Connection con = null;
Statement stmt = null;
ResultSet rs = null;
try {
con = MySQLDAOFactory.getConnection();
stmt = con.createStatement();
rs = stmt.executeQuery(MySQLQueries.SQL_GET_ALL_STATIONS);
while (rs.next()) {
stations.add(extractStation(rs));
}
} catch (SQLException e) {
throw new DAOException(Messages.CANNOT_OBTAIN_ALL_STATIONS, e);
} finally {
MySQLDAOFactory.close(con, stmt, rs);
}
return stations;
}