我应该在这里测试什么?

时间:2019-11-16 07:12:12

标签: java unit-testing mockito

我有方法,可以通过ID从数据库中删除实体:

public void delete(Integer id)  {
    try {
        connection = getNewConnection();
    } catch (SQLException e) {
        log.warning("connection error");
    }
    PreparedStatement ps = getPreparedStatement(DELETE_SMTH);
    try {
        ps.setInt(ID, id);
        ps.execute();
    } catch (SQLException e) {
        log.warning("error with statements");
    } finally {
        closeStatement(ps);
        closeConnection();
    }
}

现在,我尝试使用Mockito和TestNg创建单元测试。

@Test
public void testDelete() throws SQLException {
    Connection connectionMock = Mockito.mock(Connection.class);
    PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class);
    myDAO DAO = Mockito.mock(myDAO.class);
    Mockito.when(DAO.getNewConnection()).thenReturn(connectionMock);
    Mockito.when(DAO.getPreparedStatement(Mockito.anyString())).thenReturn(preparedStatementMock);
}

我走对了吗? 我如何完成此测试?

1 个答案:

答案 0 :(得分:1)

  1. 定义所有模拟
  2. 调用instance.delete(id)
  3. 检查所需的方法是否由“ Mockito.verify”执行

在您的情况下,我建议检查是否执行了以下方法:
        setInt(ID,id)
        execute()
        closeStatement(ps)
        closeConnection()