Mockito- 模拟数据库调用

4

我尝试使用Mockito模拟以下返回用户详细信息的方法。

但它实际上调用了数据库,而没有返回模拟结果。

我的方法-

public User getUserById(String userId){
    if (userId == null) {
        throw new IllegalArgumentException("AssociateId cannot be null");
    }
    User user = new User();
    preparedStatement = null;
    try {
        connection = dbConnection.openConnection(properties, inputStream);
        query = queryReader
                .getQuery(RelationshipManagerConstants.selectUser);
        preparedStatement = connection.prepareStatement(query);
        preparedStatement.setString(I_User.associateId, userId);
        resultSet = preparedStatement.executeQuery();
        if (resultSet.next()) {
            user.setAssociateId(resultSet.getString(I_User.associateId));
            user.setAssociatePassword(resultSet
                    .getString(I_User.associatePassword));
            user.setAssociateRole(resultSet.getInt(I_User.associateRole));
            user.setAssociateIsActive(resultSet
                    .getBoolean(I_User.associateIsActive));
            user.setAssociateEmail(resultSet
                    .getString(I_User.associateEmail));
        }
    } catch (ClassNotFoundException e) {
        LOGGER.warning("Cannot return User Details. ClassNotFoundException occured.");
    } catch (SQLException e) {
        LOGGER.warning("Cannot return User Details. SQLException occured.");
    } catch (IOException e) {
        LOGGER.warning("Cannot return User Details. IOException occured.");
    } finally {
        if (resultSet != null) {
            try {
                resultSet.close();
            } catch (SQLException e) {
                LOGGER.warning("Failed to close resultSet.");
            }
        }
        if (preparedStatement != null) {
            try {
                preparedStatement.close();
            } catch (SQLException e) {
                LOGGER.warning("Failed to close statement.");
            }
        }
        if (connection != null) {
            try {
                connection.close();
            } catch (SQLException e) {
                LOGGER.warning("Failed to close connection.");
            }
        }
    }
    return user;
}

我的测试-

@Test
public void testGetUserById() throws Exception {
    mockConnection = Mockito.mock(Connection.class);
    Properties mockProperties =  Mockito.mock(Properties.class);
    InputStream mockInputStream = Mockito.mock(InputStream.class);
    DBConnection mockDbConnection = Mockito.mock(DBConnection.class);
    PreparedStatement mockPreparedStatement = Mockito.mock(PreparedStatement.class);
    ResultSet mockResultSet = Mockito.mock(ResultSet.class);
    QueryReader mockQueryReader = Mockito.mock(QueryReader.class);


    PowerMockito.whenNew(DBConnection.class).withNoArguments()
    .thenReturn(mockDbConnection);
    PowerMockito.whenNew(QueryReader.class).withNoArguments()
    .thenReturn(mockQueryReader);


    String query = "select * from User where AssociateID=?;";
    Mockito.when(mockDbConnection.openConnection(mockProperties, mockInputStream)).thenReturn(mockConnection);
    Mockito.when(mockQueryReader.getQuery("sqlScript_selectUser.sql")).thenReturn("query");
    Mockito.when(mockConnection.prepareStatement("query")).thenReturn(mockPreparedStatement);
    Mockito.when(mockPreparedStatement.executeQuery()).thenReturn(mockResultSet);
    Mockito.when(mockResultSet.next()).thenReturn(true);

    Mockito.when(mockResultSet.getString(1)).thenReturn("message");
    User u=userDAO.getUserById("AB1234");
    assertEquals("EX112233", u.getAssociateId());
}

由于我返回的是“message”,我的测试应该失败。然而,我却使用“EX112233”进行断言。

但它却调用了数据库而不是模拟。

提前感谢您的帮助。


4
你是否考虑过使用内存数据库来测试你的DAO(数据访问对象)呢?当前的测试中使用了太多的模拟对象,会使得维护起来变得困难。 - denis.solonenko
我认为写整合测试比编写单元测试更好。 - kcon123
1个回答

0
你已经为 PowerMockito 的测试准备好 UserDAO 使用 @PrepareForTest了吗?
记住,你需要为调用 new DBConnection()new QueryReader() 的那个类进行准备,以使这些构造函数桩生效。

是的,我已经准备好了我的UserDAO。 - Veerendra Manikonda
如果你正在这样做,并且使用 PowerMockRunner 运行你的测试,那么根据你发布的代码,我不确定是否有更好的想法。 - Jeff Bowman

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接