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?
The resultSetMock.next()
method would still need to be executed at least twice. 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.
This should now provide the expected behavior when the test is exercised.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.