Warning: file_get_contents(/data/phpspider/zhask/data//catemap/9/java/385.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Java 如何在DAO层中抛出SQLException_Java_Code Coverage_Dao - Fatal编程技术网

Java 如何在DAO层中抛出SQLException

Java 如何在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

我想用JUnit测试DAO类。测试覆盖率是80%,所以几乎每一行代码都被覆盖,除了SQLException的catch子句。我不知道如何引发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);
        }
    }

在这里,你必须做一些欺骗:

  • 你的连接器对象(不管它是什么)是模拟的吗
  • 让模拟返回模拟的
    连接
  • 让模拟的
    连接
    返回模拟的
    PreparedStatement
  • 通过抛出一个
    SQLException
    ,使模拟的
    PreparedStatement
    失败
对于mockito,这可能是:

// 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()
    ,或
  • 覆盖
    DELETE\u STUDENT\u FROM\u ONE\u COURSE\u QUERY
    为无效的SQL语句

通过不存在的studentId怎么样?您好,您可以使用Mockito。您有一个引发异常的示例:@IKo,它不会导致任何更新,而不是异常。根据PreparedStatement的文档“SQLException-如果发生数据库访问错误,则在关闭的PreparedStatement上调用此方法,或者SQL语句返回ResultSet对象”。意味着您必须模拟连接器。正如@stacy所说,你可以用mockito来做。你可以考虑的一件事是,如果你真的想抓住这里的SqLExcExchange。因为只有当您遇到配置问题(如连接字符串错误)时才会出现这种情况。我认为在某些情况下,测试catch部分可能是值得的(例如,检查我们是否正确处理异常,或者它们是否与catch块无关-您不希望NPE超过SQLException:)。然而,OP希望实现最佳覆盖率(据我从测试覆盖率中了解,覆盖率为80%,因此除了SQLException的catch子句外,几乎每一行代码都被覆盖)模拟是正确的方法,我同意NoData和Stacky对Mockito的建议,以帮助您。