我尝试对该方法进行单元测试:

  @Override
    public Duck getById(Integer id)  {
        try {
            connection = getNewConnection();
        } catch (SQLException e) {
            log.warning("connection error");
        }
        PreparedStatement preparedStatement = getPreparedStatement(SELECT_DUCK_BY_ID);
        Duck duck = new Duck();
        Frog frog = new Frog();
        String temp;
        int tempInt;
        try {
            preparedStatement.setInt(ID, id);
            ResultSet resultSet = preparedStatement.executeQuery();
            while (resultSet.next()) {
                duck.id(resultSet.getInt(ID));
                if ((temp = resultSet.getString(NAME)) != null) {
                    duck.name(temp);
                } else {
                    duck.name(DEFAULT);
                }
...........


我的测试:

    @Test
    public void testGetById() throws SQLException {
        Connection connectionMock = Mockito.mock(Connection.class);
        PreparedStatement preparedStatementMock = Mockito.mock(PreparedStatement.class);
        ResultSet resultSetMock = Mockito.mock(ResultSet.class);
        DuckDAO duckDAO = Mockito.spy(DuckDAO.class);
        Mockito.when(duckDAO.getNewConnection()).thenReturn(connectionMock);
        Mockito.when(connectionMock.prepareStatement(DuckDAO.SELECT_DUCK_BY_ID)).thenReturn(preparedStatementMock);
        Mockito.when(preparedStatementMock.executeQuery()).thenReturn(resultSetMock);
//        Mockito.when(resultSetMock.next()).thenReturn(true);
        duckDAO.getById(ID);

        Mockito.verify(resultSetMock, Mockito.times(1)).getInt(DuckDAO.ID);
   }


我被注释过的行(//)将始终为真,并且循环将始终有效。如何使它只能工作1次?

最佳答案

resultSetMock.next()方法仍然需要至少执行两次。首先让它进入循环,其次让它打破循环。

设置调用该方法时要返回的连续返回值。

//...

Mockito.when(resultSetMock.next()).thenReturn(true, false);

//...


上面的代码将在第一次调用resultSetMock.next()时让true返回while使其进入false循环,而第二个调用将返回使其中断。

现在,应该可以在进行测试时提供预期的行为。

10-07 19:31
查看更多