我有一个包含Map<String,Widget>
属性的简单 POJO:
private Map<String, Widget> widgetCache = new HashMap<String, Widget>();
@Override
public Logger newWidget(String name, Widget widget) {
// First, print the contents of widgetCache in pretty print format.
Map<String, Widget> map = widgetCache;
List<String> keys = new ArrayList<String>(map.keySet());
System.out.println("Printing..." + keys.size());
for (String key: keys)
System.out.println(key + ": " + map.get(key).getName());
if(!widgetCache.containsKey(name)) {
System.err.println("I don't contain " + name);
widgetCache.put(name, widget);
}
return widgetCache.get(name);
}
很简单:它只是不允许重复Widget
的 s 被插入到地图中。当我使用 Mockito (1.9.5) 在 JUnit 测试方法中对此进行测试时:
CachingWidgetFactory fixture = new CachingWidgetFactory();
// By the way, I get errors if I try to make this next line:
// HashMap<String,Widget> mockMap = Mockito.mock(HashMap<String,Widget>.class);
// How do I enforce generics here when defining a mock?
HashMap mockMap = Mockito.mock(HashMap.class);
fixture.setLoggerCache(mockMap);
fixture.newWidget("Widget-A", new Widget("Widget-A"));
fixture.newWidget("Widget-A", new Widget("Widget-A"));
Mockito.verify(mockMap, Mockito.times(1))
.put(Mockito.anyString(), Mockito.<Logger>any());
我得到以下 JUnit 输出的测试失败:
org.mockito.exceptions.verification.TooManyActualInvocations:
hashMap.put(<any>, <any>);
Wanted 1 time:
在(STDOUT)控制台输出中,我看到了:
Printing...0
I don't contain Widget-A
Printing...0
I don't contain Widget-A
因此,看起来 Mockito 返回的模拟允许第二次(重复)插入。但是,当我完全删除 MockitomockMap
并使测试方法看起来像:
CachingWidgetFactory fixture = new CachingWidgetFactory();
fixture.newWidget("Widget-A", new Widget("Widget-A"));
fixture.newWidget("Widget-A", new Widget("Widget-A"));
然后在控制台输出中,我得到:
Printing...0
I don't contain Widget-A
Printing...1
现在(非模拟)代码正确地防止了重复插入。因此,就好像 MockitoHashMap
每次newWidget
被调用时都会返回一个新的。这里发生了什么,为什么?(如果你能在上面提到的一般问题上帮助我,还有加分。)提前致谢。