简体   繁体   English

单元测试有问题,我怎样才能让它只工作1次?

[英]Problem with unit test, how can I make it works only 1 time?

I try to make unit test of this method:我尝试对此方法进行单元测试:

  @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);
                }
...........

My test:我的测试:

    @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);
   }

Line, that I have been commented(//) will always true and my loop will always work.行,我已被评论(//)将始终正确,我的循环将始终有效。 How can I make it works only 1 time?我怎样才能让它只工作1次?

The resultSetMock.next() method would still need to be executed at least twice. resultSetMock.next()方法仍然需要至少执行两次。 First to let it enter the loop and the second to break the loop.第一个让它进入循环,第二个打破循环。

Set consecutive return values to be returned when the method is called.设置调用方法时要返回的连续返回值。

//...

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

//...

The above would let resultSetMock.next() return true when first called to let it enter the while loop and the second call will return false to discontinue.以上将让resultSetMock.next()在第一次调用时返回true以使其进入while循环,第二次调用将返回false以终止。

This should now provide the expected behavior when the test is exercised.现在,这应该在执行测试时提供预期的行为。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM