Search code examples
javacode-coveragedao

How to throw SQLException in a DAO-layer


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);
        }
    }

Solution

  • That where you have to cheat a little:

    • Have you connector object (whatever it is) be a mock
    • Have the mock returns a mocked Connection
    • Have the mocked Connection returns a mocked PreparedStatement
    • Have the mocked 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);