我想使用Mockito(和PowerMockito,如果需要)測試我的DAO方法,但我不知道如何執行此操作。調用靜態方法的最大問題(MySQLStationDAO中的MySQLDAOFactory.getConnection())。你可以幫我嗎?使用Mockito和PowerMockito進行DAO測試
我取得聯繫是這樣的:
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;
}
究竟是什麼問題?你有例外嗎? – BetaRide
我們可能還需要一些額外的信息。你的DataSource在哪裏配置? – Nitax