提问者:小点点

如何编写Junit来测试catch块


我必须为下面的方法写Junit。如何使用@ Test(expected = sqlexception . class)用Junit覆盖catch块。

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;

    }

共1个答案

匿名用户

您应该从try块中的代码创建一个内部方法(refactor extract method ), JUnit test和您的方法都将使用它:

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(...)
}