我必须为以下方法编写Junit。我如何用Junit覆盖catch块 使用@Test(expected = SQLException.class)。
public int getId(final String col1, final int col2,
String col3) throws DatabaseDownException {
final String IdQuery = "Select id from Manager where col1= ? and col2 = ? and col3 = ?";
Connection con = null;
PreparedStatement stmt = null;
ResultSet rs = null;
int Id = 0;
try {
con = getDataSource().getConnection();
stmt = con.prepareStatement(IdQuery);
stmt.setString(1, col1);
stmt.setInt(2, col2);
stmt.setString(3, col3);
rs = stmt.executeQuery();
if (null != rs && rs.next()) {
Id = rs.getInt(1);
}
} catch (SQLException e) {
logger.error("ERROR-WARNING:<<<getId():: ID "+col1+" SQLException occurred while selecting data table.");
} finally {
cleanUp(rs, stmt, con);
}
return Id;
}
答案 0 :(得分:0)
您应该从try块(重构提取方法)中的代码创建一个内部方法,JUnit测试和您的方法都将使用:
protected int getId(final String col1, final int col2, String col3, final String IdQuery, int Id) throws SQLException {
Connection con;
PreparedStatement stmt;
ResultSet rs;
con = getDataSource().getConnection();
stmt = con.prepareStatement(IdQuery);
stmt.setString(1, col1);
stmt.setInt(2, col2);
stmt.setString(3, col3);
rs = stmt.executeQuery();
if (null != rs && rs.next()) {
Id = rs.getInt(1);
}
return Id;
}
单元测试:
@Test(expected = SQLException.class)
public void testGetId() {
getId(...)
}