java - 使用 jdbcTemplate 和 DAO 层在 jUnit 中测试删除方法

标签 java spring unit-testing spring-mvc junit

我正在尝试测试我的删除方法,但我不知道该怎么做,我尝试在测试删除方法中使用我删除的用户的 id 调用我的 searchByID 以创建一个 null 变量,然后使用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

我创建了这个建议的方法,但它给了我一个错误,我缺少返回值,所以我添加了 return 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

我尝试使用此设置将用户设置为空,因此如果出现异常,我的方法将返回空对象,但当我尝试使用异常方法时,我在单元测试中仍然遇到相同的问题

@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

最佳答案

问题出在您的方法 serachUserById() 中。我在下面的代码中为您修复了它。您总是返回一个用户对象。无论数据库中是否存在用户。下面的代码首先将 null 分配给用户。我猜如果没有具有此 userId 的用户,则会出现异常。所以你捕获异常并继续返回 null。如果数据库中有用户,您将创建一个 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 和存储过程。您将节省大量时间并减少错误。

关于java - 使用 jdbcTemplate 和 DAO 层在 jUnit 中测试删除方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28974451/

相关文章:

unit-testing - 在域类上调用 .save() 失败,单元测试中没有方法 .save() 的签名

c# - 犀牛模拟 : AssertWasCalled doesn't work on Stub

asp.net-mvc - 如何使用 ASP.NET MVC 的最小起订量模拟 Request.ServerVariables?

java - @EJB 返回 null

java - 保持文件句柄打开,还是根据需要重新打开?

java - jtable复选框单选java swing

java - 无法通过jpa存储库删除记录

java - 如果字段是另一个类,则访问 jSTL 中类的字段

java - 如何知道 Spring Boot 中的 webjars 路径。如何获取 webjars 中所有可用文件的路径

java - 如何将 Hibernate 与映射到不同数据库的自定义字段类型一起使用?