使用jdbcTemplate和DAO Layer测试jUnit中的delete方法

时间:2015-03-10 21:30:11

标签: java spring unit-testing spring-mvc junit

我正在尝试测试我的删除方法,但我不知道我该怎么做,我尝试在我的测试删除方法中调用我的searchByID,其中我删除了用户的id以创建一个空变量然后使用assertNull

像这样:

    @Test
    public void deleteUser() 
    {

        userDAO.deleteUserById(3);
        User nullUser  =  userDAO.searchUserById(3);
        assertNull(nullUser);
    }

但这给了我这个错误:

expected null but was domain.User@c506pb

我尝试使用异常方法,因为我可以在输出中知道该代码生成java.sql.SQLException: ORA-01403: no data found  我试过这样:

    @Test(expected=SQLException.class)
    public void deleteUser() 
    {

         userDAO.deleteUserById(3);
        Usuario usuarioVacio  =  usuarioDAO.buscarUsuarioPorId(3);

    }

但这给了我这个错误:

Expected exception: java.sql.SQLException
java.lang.AssertionError

这是我的删除方法实现

@Override
public void deleteUserById(int idUser)
{

    Connection connection = null;
    try {

        String storedProcedure =  "{ call deleteUserById(?) }";

        connection  =  jdbcTemplate.getDataSource().getConnection();
        CallableStatement callableStatement = connection.prepareCall(storedProcedureBorrarUSuario);

        callableStatement.setInt(1, idUser);

        callableStatement.executeQuery();
    } 
    catch (SQLException ex) 
    {

        ex.printStackTrace();
    }
    finally 
    {
        if(connection != null)
        try 
        {
            connection.close();
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }
}

该方法有效,因为它删除了正确的用户,我想使用异常方法和另一种方法来实现它,但我不知道为什么不工作

编辑:

这是我的searchById方法

@Override
    public Usuario buscarUsuarioPorId(int userId) 
    {
        User user=  new  User();
        Connection connection = null;
        try {
            String storedProcedureInfoUsuario  =  "{ call searchUserById(?, ?, ?, ?, ?) }";

            connection  =  jdbcTemplate.getDataSource().getConnection();
            CallableStatement callableStatement = connection.prepareCall(storedProcedureInfoUsuario);

            callableStatement.setInt(1, idUsuario);
            callableStatement.registerOutParameter(2, Types.VARCHAR);
            callableStatement.registerOutParameter(3, Types.VARCHAR);
            callableStatement.registerOutParameter(4, Types.VARCHAR);
            callableStatement.registerOutParameter(5, Types.VARCHAR);

            callableStatement.executeQuery();

            //
            user.setName(callableStatement.getString(2));
            user.setLastName(callableStatement.getString(3));
            user.setEmail(callableStatement.getString(4));
            user.setState(callableStatement.getString(5));
        } 
        catch (SQLException ex) 
        {
//          Logger.getLogger(UsuarioDAOImplementacion.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        finally 
        {
            if(connection != null)
            try 
            {
                connection.close();
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
        }
        return usuario;
    }

这是我的PL / SQL searchById

CREATE OR REPLACE PROCEDURE searchUserById
    (
       p_userId IN User.user_id%TYPE,
       ps_name OUT User.name%TYPE,
       ps_lastName OUT User.lastName%TYPE,
       ps_email OUT User.email%TYPE,
       ps_state OUT User.state%TYPE
    )
IS
BEGIN

  SELECT name, lastName, email, state
  INTO ps_name , ps_lastName , ps_email , ps_state 
  FROM  USER WHERE user_id= p_userid;

END;
/

这是我的删除PL / SQL

CREATE OR REPLACE PROCEDURE deleteUserById
    (
       p_userId IN USER.user_ID%TYPE
    )
IS
BEGIN

  DELETE FROM USER
  WHERE user_id=p_userId;
COMMIT;
END;
/

编辑2

我创建了这个建议的方法,但它给了我一个错误,我错过了一个返回值所以我添加了返回null

 @Override
public void deleteUserById(final int idUser) {

    final String storedProcedureBorrarUSuario =  "{ call borrarUsuarioPorId(?) }";
    final Connection connection = null;

    jdbcTemplate.execute( new ConnectionCallback<Object>() 
    {
        @Override
        public Object doInConnection(Connection con) throws SQLException, DataAccessException 
        {
            CallableStatement callableStatement = connection.prepareCall(storedProcedureBorrarUSuario);
            callableStatement.setInt(1, idUser);
            callableStatement.executeUpdate();
            return null;

        }
    });   
}

当我运行我的单元测试时,它会在此行中显示空指针异常

userDAO.deleteUserById(3);

编辑3

我尝试使用此seting将用户视为null,因此如果有异常,我的方法会返回一个null对象,但是当我尝试使用异常方法时,我的单元测试仍然存在同样的问题

@Override
public Usuario searchUserById(int userId) 
{
    User user=  null;
    Connection connection = null;

    try {
        String storedProcedureInfoUsuario  =  "{ call searchUserById(?, ?, ?, ?, ?) }";

        connection  =  jdbcTemplate.getDataSource().getConnection();
        CallableStatement callableStatement = connection.prepareCall(storedProcedureInfoUsuario);

        callableStatement.setInt(1, userId);
        callableStatement.registerOutParameter(2, Types.VARCHAR);
        callableStatement.registerOutParameter(3, Types.VARCHAR);
        callableStatement.registerOutParameter(4, Types.VARCHAR);
        callableStatement.registerOutParameter(5, Types.VARCHAR);

        callableStatement.executeQuery();

        //
        user=  new User();
        usuario.setName(callableStatement.getString(2));
        usuario.setLastName(callableStatement.getString(3));
        usuario.setEmail(callableStatement.getString(4));
        usuario.setState(callableStatement.getString(5));
    } 
    catch (SQLException ex) 
    {
//          Logger.getLogger(UsuarioDAOImplementacion.class.getName()).log(Level.SEVERE, null, ex);
            ex.printStackTrace();
        }
        finally 
        {
            if(connection != null)
            try 
            {
                connection.close();
            } 
            catch (SQLException e) 
            {
                e.printStackTrace();
            }
        }
        return user;
    }

这是我的单元测试,我期望有一个空值,这适用于我做的修改

public void findUserById()
{
    User emptyUser=  userDAO.searchUserById(50);
    assertNull(emptyUser);
}

但是如果我尝试使用异常方法,则会出现以下错误

@Test(expected=SQLException.class) 
public void findUserById()
    {
        User emptyUser=  userDAO.searchUserById(50);
        assertNull(emptyUser);
    }

这给了我Expected exception: java.sql.SQLException java.lang.AssertionError

我不知道为什么如果我的输出中有以下异常,这不起作用 java.sql.SQLException: ORA-01403: no data found

3 个答案:

答案 0 :(得分:1)

问题在于你的方法serachUserById()。我在下面的代码中为你修复了它。您总是返回一个用户对象。无论数据库中是否有用户。下面的代码首先将null分配给用户。如果没有这个userId的用户,我想有一个例外。所以你捕获异常并继续返回null。如果DB中有用户,您将创建一个User对象,请用值填充并返回该对象。

关键是区分 1.有一个用户,我用User对象返回它 2.没有用户,我返回null。

@Override
public User serachUserById(int userId) 
{
    User user = null;
    Connection connection = null;
    try {
        String storedProcedureInfoUsuario  =  "{ call searchUserById(?, ?, ?, ?, ?) }";

        connection  =  jdbcTemplate.getDataSource().getConnection();
        CallableStatement callableStatement = connection.prepareCall(storedProcedureInfoUsuario);

        callableStatement.setInt(1, userId);
        callableStatement.registerOutParameter(2, Types.VARCHAR);
        callableStatement.registerOutParameter(3, Types.VARCHAR);
        callableStatement.registerOutParameter(4, Types.VARCHAR);
        callableStatement.registerOutParameter(5, Types.VARCHAR);

        callableStatement.executeQuery();

        //
        user = new User();
        user.setName(callableStatement.getString(2));
        user.setLastName(callableStatement.getString(3));
        user.setEmail(callableStatement.getString(4));
        user.setState(callableStatement.getString(5));
    } 
    catch (SQLException ex) 
    {

Logger.getLogger(UsuarioDAOImplementacion.class.getName()).log(Level.SEVERE, null, ex);
        ex.printStackTrace();
    }
    finally 
    {
        if(connection != null)
        try 
        {
            connection.close();
        } 
        catch (SQLException e) 
        {
            e.printStackTrace();
        }
    }
    return user;
}

无论如何,我建议你使用spring jpa存储库而不是jdbc连接,SQL和存储过程。你将节省大量的时间和错误。

答案 1 :(得分:0)

可能存在以下可能性

  1. PL / SQL中存在问题。 看看你什么时候得到那个例外?删除用户或搜索用户时。

  2. 在测试上下文的事务配置中为defaultRollback设置的配置值是什么?如果确实这意味着您的更改在执行测试方法后会回滚,这就是您可能在搜索用户中获得价值的原因

  3. 如果其他一切都是正确的话,那么交易边界可能会出现问题。

答案 2 :(得分:0)

对于初学者,我建议你重写JDBC代码并实际使用JdbcTemplate。不要自己管理连接,而是将您的逻辑包装在ConnectionCallback中,以免打开/关闭连接。

对于修改,您应该使用executeUpdate ins

@Override
public void deleteUserById(final int idUser) {
    final String storedProcedure =  "{ call deleteUserById(?) }";
    getJdbcTemplate().execute(new ConnectionCallback<Object>() {
        public Object doInConnection(Connection con) throws SQLException, DataAccessException {
            CallableStatement callableStatement = con.prepareCall(storedProcedureBorrarUSuario);
            callableStatement.setInt(1, idUser);
            callableStatement.executeUpdate();
            return null;
        }
    });   
}

@Override
public Usuario buscarUsuarioPorId(final int userId) {       
    User user=  new  User();
    final String storedProcedureInfoUsuario  =  "{ call searchUserById(?, ?, ?, ?, ?) }";
    return getJdbcTemplate().execute(new ConnectionCallback<User>() {
        public User doInConnection(Connection con) throws SQLException, DataAccessException {
        CallableStatement callableStatement = con.prepareCall(storedProcedureInfoUsuario);

        callableStatement.setInt(1, idUsuario);
        callableStatement.registerOutParameter(2, Types.VARCHAR);
        callableStatement.registerOutParameter(3, Types.VARCHAR);
        callableStatement.registerOutParameter(4, Types.VARCHAR);
        callableStatement.registerOutParameter(5, Types.VARCHAR);

        callableStatement.executeQuery();
        //
        user.setName(callableStatement.getString(2));
        user.setLastName(callableStatement.getString(3));
        user.setEmail(callableStatement.getString(4));
        user.setState(callableStatement.getString(5));

    });
}