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!
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 Answer
s:
when(rs.next()).thenAnswer(new Answer() {
private int iterations = 2;
Object answer(InvocationOnMock invocation) {
return iterations-- > 0;
}
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With