如何编写Junit来测试catch块

如何编写Junit来测试catch块,junit,Junit,我必须为下面的方法编写Junit。我如何用Junit覆盖catch block 使用@Test(预期=SQLException.class) public int getId(最终字符串col1,最终int col2, 字符串col3)引发DatabaseDownException{ 最后一个字符串IdQuery=“从管理器中选择id,其中col1=?和col2=?以及col3=?”; 连接con=null; PreparedStatement stmt=null; 结果集rs=null; in

我必须为下面的方法编写Junit。我如何用Junit覆盖catch block 使用@Test(预期=SQLException.class)

public int getId(最终字符串col1,最终int col2,
字符串col3)引发DatabaseDownException{
最后一个字符串IdQuery=“从管理器中选择id,其中col1=?和col2=?以及col3=?”;
连接con=null;
PreparedStatement stmt=null;
结果集rs=null;
int Id=0;
试一试{
con=getDataSource().getConnection();
stmt=con.preparest陈述(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);
}
}捕获(SQLE异常){

error(“error-WARNING:您应该从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(...)
}

您想知道SQLException是在方法中抛出的,catch在方法中?请参阅我想在junit中覆盖catch块。我想将值传递给此方法,以便它抛出SQLException。我将在junit测试方法中检查它,比如@test(expected=SQLException.class)。只想覆盖异常场景。在getId()中传递什么参数因此,SQLException发生,testGetId()通过。@Arpan Paliwal您应该决定要检查什么,最简单的方法是将无效查询作为
sele
放入
IdQuery
参数。我不能更改getId方法,也不能通过查询,我可以通过测试方法传递col1、col2、col3值,这些参数如何创建无效查询。请查看我的方法签名。@ARPANPLIWAL i如果无法更改,请尝试在
col1
parmeter中发送null
@Test(expected = SQLException.class)
public void testGetId() {
   getId(...)
}