Muhammad Suleman Muhammad Suleman - 5 months ago 140
Java Question

How to mock ResultSet.next() method using Mockito

I am mocking

java.sql.ResultSet
like this

ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true); // this seems wrong appraoch


Test code is like this

while (rs.next()) {
// doing stuff here
}


So problem is when I have mock
rs.next()
to
true
then
while
loop never terminates. I want to terminate
while
loop after 2 iteration. So how i can mock
rs.next()
method?

I have also tried

when(rs.next()).thenReturn(true, true, false); // always return false


Please help!

Answer

You can chain doReturn() method calls:

doReturn(true).doReturn(true).doReturn(false).when(rs).next();

Or, as mentioned in the comments, chain thenReturn method calls:

when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);

Or, if you want to take things even further, you can use Mockito Answers:

when(rs.next()).thenAnswer(new Answer() {
    private int iterations = 2;

    Object answer(InvocationOnMock invocation) {
        return iterations-- > 0;
    }
});