java 如何使用 Mockito 模拟 ResultSet.next() 方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32088073/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to mock ResultSet.next() method using Mockito
提问by Muhammad Suleman
I am mocking java.sql.ResultSet
like this
我嘲笑java.sql.ResultSet
这样的
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?
所以,问题是,当我有模拟rs.next()
到true
再while
循环永远不会终止。我想while
在 2 次迭代后终止循环。那么我如何模拟rs.next()
方法?
I have also tried
我也试过
when(rs.next()).thenReturn(true, true, false); // always return false
Please help!
请帮忙!
回答by Robby Cornelissen
You can chain doReturn()
method calls:
您可以链接doReturn()
方法调用:
doReturn(true).doReturn(true).doReturn(false).when(rs).next();
Or, as mentioned in the comments, chain thenReturn
method calls:
或者,如评论中所述,链式thenReturn
方法调用:
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
Or, if you want to take things even further, you can use Mockito Answer
s:
或者,如果你想更进一步,你可以使用 Mockito Answer
s:
when(rs.next()).thenAnswer(new Answer() {
private int iterations = 2;
Object answer(InvocationOnMock invocation) {
return iterations-- > 0;
}
});
回答by aro_tech
Try
尝试
when(rs.next()).thenReturn(true).thenReturn(true).thenReturn(false);
回答by Brice
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.
您不应该模拟 JDBC 类,而应该创建一个带有真实数据库的集成测试。还要注意ResultSet
确实是一个接口,但驱动程序/数据库可能在行为上有一些差异。这种嘲笑这些的测试使开发人员对真实的生产行为视而不见。
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.
如果这段代码只是处理返回的数据而不是实际的 JDBC 调用代码,那么这段代码应该与 JDBC 类解耦,因为它ResultSet
不应该被导入。从长远来看,它有助于将技术代码与业务代码分开。
回答by Rainbow702
when(rs.next()).thenReturn(true, true, false);
this should work.
这应该有效。
i find an example from the javadoc of 'mockito-core:1.10.19'.
我从'mockito-core:1.10.19'的javadoc中找到了一个例子。
take a look at this: org.mockito.Mockito.when
看看这个: org.mockito.Mockito.when