Java 如何使用 Mockito 模拟 For 循环
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/20007171/
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 a For Loop using Mockito
提问by Vikram
I'm a newbie to mockito. My question is how can I mock a for loop using Mockito?
我是 mockito 的新手。我的问题是如何使用 Mockito 模拟 for 循环?
For Eg: This is the main Class:
例如:这是主类:
import java.util.HashSet;
import java.util.Set;
public class stringConcatination {
public static void main(String[] args) {
Set<String> stringSet = new HashSet();
stringSet.add("Robert");
stringSet.add("Jim");
for (String s:stringSet) {
s = "hi " + s;
}
}
}
This is the Test Class:
这是测试类:
import java.util.HashSet;
import java.util.Set;
import org.junit.Test;
import static org.mockito.Mockito.mock;
public class stringConcatinationTest {
@Test
public void testMain() {
Set mockSet = mock(HashSet.class);
// -- How to mock For Loop --
}
}
I saw this related question. But I couldn't understand, how a for loop can be mocked.
我看到了这个相关的问题。但我无法理解,如何模拟 for 循环。
采纳答案by Rangi Lin
Since the for loop is just the syntax sugar of iterator()
loop, you could just stub the method and return the mocked Iterator
instance
由于 for 循环只是循环的语法糖iterator()
,您可以只存根该方法并返回模拟Iterator
实例
回答by Jeff Bowman
It is almost always a better idea to use real collections, such as ArrayList for a List implementation or HashSet for a Set implementation. Reserve your use of Mockito for collaborators that interact with external services or that have side effects, or that calculate hard-to-predict values, or that don't exist when you write your system under test. Collections in particular fail all three of these conditions.
使用真正的集合几乎总是一个更好的主意,例如 ArrayList 用于 List 实现或 HashSet 用于 Set 实现。将 Mockito 的使用保留给与外部服务交互或有副作用、或计算难以预测的值或在编写测试系统时不存在的协作者。特别是集合无法满足所有这三个条件。
To test a for loop, extract it to a method that takes a Collection or Iterable, and then create a List in your test to pass in. Your code will wind up more reliable and easier to follow because of it.
要测试 for 循环,请将其提取到采用 Collection 或 Iterable 的方法,然后在测试中创建一个 List 以传入。因此,您的代码将变得更可靠且更易于遵循。
回答by leojh
Also, you may use a Spy to deal with the real implementation vs. a mock. For collections, in particular, this may be a better approach then mocking them.
此外,您可以使用 Spy 来处理实际实现与模拟。特别是对于集合,这可能是一种比模拟它们更好的方法。
@Spy
private Set<String> mySet = new HashSet<String>()
{{
add("john");
add("jane");
}};
回答by Aldian Fazrihady
There is a feature in Mockito that can handle method call mocking inside iteration block. This is clearly explained at http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#stubbing_consecutive_calls
Mockito 中有一个功能可以处理迭代块内的方法调用模拟。这在http://site.mockito.org/mockito/docs/current/org/mockito/Mockito.html#stubbing_consecutive_calls 中有清楚的解释