Java 如何在DAO层中抛出SQLException
我想用JUnit测试DAO类。测试覆盖率是80%,所以几乎每一行代码都被覆盖,除了SQLException的catch子句。我不知道如何引发SQLExceptionJava 如何在DAO层中抛出SQLException,java,code-coverage,dao,Java,Code Coverage,Dao,我想用JUnit测试DAO类。测试覆盖率是80%,所以几乎每一行代码都被覆盖,除了SQLException的catch子句。我不知道如何引发SQLException public void removeStudentFromCourse(Integer studentId, Integer courseId) { try (Connection connection = connector.getConnection(); PreparedStatem
public void removeStudentFromCourse(Integer studentId, Integer courseId) {
try (Connection connection = connector.getConnection();
PreparedStatement statement = connection.prepareStatement(
DELETE_STUDENT_FROM_ONE_COURSE_QUERY)) {
statement.setInt(1, studentId);
statement.setInt(2, courseId);
statement.executeUpdate();
} catch (SQLException e) {
throw new DBException("Can`t remove student with id: " + studentId +
" from course with id:" + courseId, e);
}
}
在这里,你必须做一些欺骗:
- 你的连接器对象(不管它是什么)是模拟的吗
- 让模拟返回模拟的
连接
- 让模拟的
返回模拟的连接
PreparedStatement
- 通过抛出一个
,使模拟的SQLException
失败PreparedStatement
// case 1
when(connector.getConnection()).thenThrow(SQLException.class);
// case 2
Connection cnx = mock(Connection.class);
when(cnx.prepareStatement(anyString()).thenThrow(SQLException.class);
when(connector.getConnection()).thenReturn(cnx);
when(connector.getConnection()).thenThrow(SQLException.class);
你可以
- 拥有一个调用时抛出
到SQLException
getConnection()
- 拥有一个生成模拟PreparedStatement的连接,该语句在调用的某个方法上抛出
,如SqlException
或setInt()
,或executeUpdate()
- 覆盖
为无效的SQL语句DELETE\u STUDENT\u FROM\u ONE\u COURSE\u QUERY