为什么我的检索数据的单元测试在主方法中显示为null,它显示为Integer



我正在编写一个代码的单元测试,该代码使用JDBC 从数据库中检索价格

public PPrice getPriceByZoneId(int zoneId) throws DatabaseLayerException {
PPrice foundPrice = null;

Calendar calendar = Calendar.getInstance();
java.sql.Date dateNow = new java.sql.Date(calendar.getTime().getTime());

Connection con = DBConnection.getInstance().getDBcon();
String baseSelect = "select top 1 price, pZone_id from PPrice ";
baseSelect += "where pZone_id = " + zoneId + " and starttime < '" + dateNow + "' ";
baseSelect += "order by starttime desc";
System.out.println(baseSelect);
/*ResultSet rs = null; 
int price, pZoneId;
PZone pZone; 
*/
try {
Statement stmt = con.createStatement();
stmt.setQueryTimeout(5);
// Todo: Get PPrice object
ResultSet rs = stmt.executeQuery(baseSelect);
/*
* Insert code 
*/

while(rs.next()) {
System.out.println("Price of zoneId  "  + zoneId  + " is " +  rs.getInt("price"));
}
stmt.close();
} catch (SQLException ex) {
foundPrice = null;
DatabaseLayerException dle = new DatabaseLayerException("Error retrieving data");
dle.setStackTrace(ex.getStackTrace());
throw dle;
} catch (NullPointerException ex) {
foundPrice = null;
DatabaseLayerException dle = new DatabaseLayerException("Null pointer exception - possibly Connection object");
dle.setStackTrace(ex.getStackTrace());
throw dle;
} catch (Exception ex) {
foundPrice = null;
DatabaseLayerException dle = new DatabaseLayerException("Data not retrieved! Technical error");
dle.setStackTrace(ex.getStackTrace());
throw dle;
} finally {
DBConnection.closeConnection();
}


return foundPrice;
}

public static void main(String[] args) {
DatabasePPrice a = new DatabasePPrice();
try {
a.getPriceByZoneId(1) ;
}

catch (DatabaseLayerException g) {
System.out.println("Fail" + a);

} finally {
DBConnection.closeConnection();
}
}

结果是它返回35,这是正确的。

问题是当我使用JUnit编写单元测试时。它显示实际结果为null,但应该为35。我很困惑。有人能看出错误吗?

这是我写的单元测试

@Test
public void wasRetrievedPriceDatabaselayer() throws DatabaseLayerException {
// Arrange
Calendar calendar = Calendar.getInstance();
java.sql.Date dateNow = new java.sql.Date(calendar.getTime().getTime());

Connection con = DBConnection.getInstance().getDBcon();
// Act
DatabasePPrice a = new DatabasePPrice();
try {
a.getPriceByZoneId(1) ;
}

catch (DatabaseLayerException g) {
System.out.println("Fail" + a);

} finally {
DBConnection.closeConnection();
}
// Assert 
assertEquals(35, a.getPriceByZoneId(1));
}

您可以在try块内调用assertEquals,而不是在末尾,因为连接将在finally块中关闭。此外,删除对a.getPriceByZoneId(1)的不必要调用

最新更新