Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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!

like image 750
Muhammad Suleman Avatar asked Aug 19 '15 06:08

Muhammad Suleman


1 Answers

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;
    }
});
like image 137
Robby Cornelissen Avatar answered Nov 05 '22 19:11

Robby Cornelissen