如何使用Mockito模拟ResultSet.next()方法

Muh*_*man 6 java unit-testing mockito

我嘲笑java.sql.ResultSet这样的

ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true); // this seems wrong appraoch
Run Code Online (Sandbox Code Playgroud)

测试代码是这样的

while (rs.next()) {
  // doing stuff here
}
Run Code Online (Sandbox Code Playgroud)

所以,问题是,当我有模拟rs.next()truewhile循环永远不会终止.我希望while在2次迭代后终止循环.那么我怎么可以模拟rs.next()方法呢?

我也试过了

when(rs.next()).thenReturn(true, true, false); // always return false 
Run Code Online (Sandbox Code Playgroud)

请帮忙!

Rob*_*sen 10

你可以链接doReturn()方法调用:

doReturn(true).doReturn(true).doReturn(false).when(rs).next();
Run Code Online (Sandbox Code Playgroud)

或者,如评论中所述,链式thenReturn方法调用:

when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
Run Code Online (Sandbox Code Playgroud)

或者,如果你想更进一步,你可以使用Mockito Answer:

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

    Object answer(InvocationOnMock invocation) {
        return iterations-- > 0;
    }
});
Run Code Online (Sandbox Code Playgroud)

  • 你也可以链接 thenReturn:when(rs.next()).thenReturn(true).thenReturn(false) (2认同)
  • 刚刚使用 Mockito 1.10.19 在本地进行了测试。我的代码按预期工作。 (2认同)

aro*_*ech 5

尝试

when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
Run Code Online (Sandbox Code Playgroud)