Java mockito 模拟集
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7193061/
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
Java mockito mock set
提问by user710818
Is possible mock set so after use in cycle e.g.
是否可以模拟设置,以便在循环中使用后,例如
for(String key: mySet) { ...}
Thanks.
谢谢。
回答by nicholas.hauschild
There is a couple options:
有几个选项:
- Cast it
- Use @Mock annotation
- 投它
- 使用@Mock 注释
Examples:
例子:
Set<String> mySet = (Set<String>) mock(Set.class);
--or--
- 或者 -
@Mock
private Set<String> mySet;
@Before
public void doBefore() throws Exception {
MockitoAnnotations.initMocks(this.getClass()); //this should create mocks for your objects...
}
回答by leo
While in the answer from nicholas is perfectly clear explaining how you mock a Set, I think your question also implies that you want to mock the behavior of the set during the loop.
虽然在 nicholas 的回答中非常清楚地解释了您如何模拟 Set,但我认为您的问题还暗示您想在循环期间模拟 Set 的行为。
To achieve that you first need to know that your code is only syntactic sugar and expands to:
要实现这一点,您首先需要知道您的代码只是语法糖并扩展为:
for (Iterator iterator = mySet.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
...
}
(For details about that see the Stackoverflow question Which is more efficient, a for-each loop, or an iterator?)
(有关详细信息,请参阅 Stackoverflow 问题哪个更有效,for-each 循环还是迭代器?)
This makes clear that you need to mock the iterator()
method. After you set up the mock as described by nicholas you mock the iterator method like this:
这清楚地表明您需要模拟该iterator()
方法。在按照 nicholas 的描述设置模拟之后,您可以像这样模拟迭代器方法:
when(mySet.iterator()).thenAnswer(new Answer<Iterator<String>>() {
@Override
public Iterator<String> answer(InvocationOnMock invocation) throws Throwable {
return Arrays.asList("A", "B").iterator();
}
});