如何模拟地图的返回值? [英] How to mock the return value of a Map?
本文介绍了如何模拟地图的返回值?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有如下代码:
for (Map.Entry<Integer, Action> entry : availableActions.entrySet()) {
...
}
我试图这样模拟它:
Map mockAvailableActions = mock(Map.class, Mockito.RETURNS_DEEP_STUBS);
mockAvailableActions.put(new Integer(1), mockAction);
我认为就足够了.但是entrySet为空.所以我添加了这个:
I would think that would be enough. But entrySet is empty. So I added this:
when(mockAvailableActions.entrySet().iterator()).thenReturn(mockIterator);
when(mockIterator.next()).thenReturn(mockAction);
仍然entrySet为空.我究竟做错了什么?感谢您的输入!
Still entrySet is empty. What am I doing wrong? Thanks for any input!
推荐答案
也许我遗漏了一些东西,但为什么不这样做呢?
Perhaps I'm missing something, but why not just do this:
Map.Entry<Integer, Action> entrySet = <whatever you want it to return>
Map mockAvailableActions = mock(Map.class);
when(mockAvailableActions.entrySet()).thenReturn(entrySet);
还要考虑您是否真的需要模拟地图,难道不是一个真正的人吗?嘲笑通常用于替换您不想参与单元测试的其他代码,Map是Java核心语言的一部分,通常不被嘲弄.
Also consider whether you actually need a mock Map at all, wouldn't a real one do the job? Mocks are usually used to replace other pieces of your code which you don't want to be involved in your unit test, a Map is part of the core Java language and isn't usually mocked out.
这篇关于如何模拟地图的返回值?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文