I want to test DAO class with JUnit. The test coverage is 80%, so nearly every line of code is covered except the catch clauses for SQLException. I have no idea how I can provoke a SQLException
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);
}
}
That where you have to cheat a little:
Connection
Connection
returns a mocked PreparedStatement
PreparedStatement
fails by throwing a SQLException
.With mockito this could be:
// 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);