Muhammad Suleman
Muhammad Suleman

Reputation: 2922

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!

Upvotes: 18

Views: 24640

Answers (4)

Rainbow702
Rainbow702

Reputation: 1

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

this should work.

i find an example from the javadoc of 'mockito-core:1.10.19'.

take a look at this: org.mockito.Mockito.when

Upvotes: 0

bric3
bric3

Reputation: 42223

While other answers are technically correct (if doesn't work in your code then maybe something else is in play and more code is needed). They all miss a vital point:

You should not mock JDBC classes but instead create an integration test with a real database behind. Also beware ResultSet is indeed an interface but drivers / DB may have some differences in behavior. Such test that are mocking those, makes developers blind to real production behaviors.

And if this code is just about handling data that is returned not the actual JDBC invocation code, then this code should be decoupled of JDBC classes in that ResultSet should not be imported. In the long run it helps to split technical code from business code.

Upvotes: 0

Robby Cornelissen
Robby Cornelissen

Reputation: 97140

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

Upvotes: 31

aro_tech
aro_tech

Reputation: 1143

Try

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

Upvotes: 5

Related Questions