我正在尝试为以下代码编写测试用例
public boolean discharge(RegBean reg_data) {
boolean status = false;
try{
con = dbConObj();
PreparedStatement pst = con.prepareStatement("select * from patient where patientid=?");
pst.setString(1,reg_data.getpatientID());
ResultSet rs = (ResultSet) pst.executeQuery();
if (rs.next()){
String docname=rs.getString("docname").trim();
String pstatus=rs.getString("status").trim();
PreparedStatement ps=con.prepareStatement("update patient set ddate=?,status=? where patientID=?");
if (pstatus.equalsIgnoreCase("Active"))
{
ps.setString(1,new java.util.Date().toString());
ps.setString(2,"Discharged");
PreparedStatement pst1=con.prepareStatement("insert into history values(?,?,?,?)");
pst1.setString(1,docname);
pst1.setString(2,reg_data.getpatientID());
pst1.setString(3,"Discharged");
pst1.setString(4,new java.util.Date().toString());
pst1.executeUpdate();
}
else
if (pstatus.equalsIgnoreCase("Discharged"))
{
ps.setString(1,"");
ps.setString(2,"Active");
PreparedStatement pst1=con.prepareStatement("insert into history values(?,?,?,?)");
pst1.setString(1,docname);
pst1.setString(2,reg_data.getpatientID());
pst1.setString(3,"Active");
pst1.setString(4,new java.util.Date().toString());
pst1.executeUpdate();
9
}
ps.setString(3,reg_data.getpatientID());
ps.executeUpdate();
}
status = true;
}
catch(Exception e){
e.printStackTrace();
return status;
}
return status;
}
[在第一个if(rs.next())
的情况下,我模拟了rs
,并且能够对其进行测试并获得覆盖。但是在第二个情况下,如果if (pstatus.equalsIgnoreCase("Active"))
pstatus是变量,并且我不能使用DoReturn.when(mockedmethod)。有什么测试方法可以让我获得使用JUnit运行时的测试覆盖率吗?
如果您已经成功地模拟了rs.next()的ResultSet,那么您也应该能够做到
when(rs.getString("status")).thenReturn("Active");
[我将尝试将方法分解为以模拟类型作为参数的较小方法。它简化了整个测试用例,因为您不必准备和检查高度嵌套的模拟。同样可以帮助处理语句类型。
旁注:您可能要在返回之前关闭ResultSet和Statements。