![](/img/trans.png)
[英]How to use resultset.next method after executing result.beforeFirst in java using mysql
[英]How to mock ResultSet.next() method using Mockito
我像这样嘲笑java.sql.ResultSet
ResultSet rs = mock(ResultSet.class);
when(rs.next()).thenReturn(true); // this seems wrong appraoch
测试代码是这样的
while (rs.next()) {
// doing stuff here
}
所以,问题是,当我有模拟rs.next()
来true
然后while
循环永远不会终止。 我希望在2次迭代后终止while
循环。 那么我怎么能模拟rs.next()
方法呢?
我也试过了
when(rs.next()).thenReturn(true, true, false); // always return false
请帮忙!
你可以链接doReturn()
方法调用:
doReturn(true).doReturn(true).doReturn(false).when(rs).next();
或者,如评论中所述,链接thenReturn
方法调用:
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
或者,如果你想更进一步,你可以使用Mockito Answer
:
when(rs.next()).thenAnswer(new Answer() {
private int iterations = 2;
Object answer(InvocationOnMock invocation) {
return iterations-- > 0;
}
});
尝试
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
虽然其他答案在技术上是正确的( 如果在您的代码中不起作用,那么可能还有其他东西正在运行,需要更多代码 )。 他们都错过了一个重要的观点:
您不应该模拟JDBC类,而是创建一个后面有真实数据库的集成测试。 还要注意ResultSet
确实是一个接口,但驱动程序/ DB可能在行为上有一些差异。 这种模仿那些的测试使开发人员对实际生产行为视而不见。
如果此代码只是处理返回的数据而不是实际的JDBC调用代码,那么此代码应该解耦为不应导入ResultSet
的JDBC类。 从长远来看,它有助于从业务代码中分离技术代码。
when(rs.next()).thenReturn(true, true, false);
这应该工作。
我从'mockito-core:1.10.19'的javadoc中找到了一个例子。
看看这个: org.mockito.Mockito.when
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.