【发布时间】:2016-08-21 01:36:15
【问题描述】:
我发现可以使用另一个 HashMap 的值来初始化 java EnumMap,但这是在测试中。我不需要使用高效的双括号或类似的东西,我只需要从给定的地图创建地图。
public EnumMap<ITEMS, Map<String, Double>> getPromotionItems(String state, Map<String, Double> prices) {
EnumMap<ITEMS, Map<String, Double>> promoItems = new EnumMap<>(ITEMS.class);
Iterator iterator = prices.entrySet().iterator();
Iterator keys = prices.keySet().iterator();
HashMap map = new HashMap<String, Double>();
while(keys.hasNext()) {
map.put(iterator.next(),keys.next());
}
promoItems.put(ITEMS.valueOf(state),map);
return promoItems;
}
我在用 Junit 写,这说明我的迭代器在某种程度上是错误的
java.lang.AssertionError: expected: java.util.EnumMap<{ORIGINAL={ProductC=3.0, ProductA=1.0, ProductB=2.0}}> but was: java.util.EnumMap<{ORIGINAL={ProductC=3.0, ProductA=1.0, ProductB=2.0}}>
解决方案 我只需要在我的类中使用一个 enumMap 并使用测试类 enumMap 调用该方法的单元测试。
这是在我的测试类中:TestClassForItems.java 公共枚举项目{ ONPROMO,原创,OFFPROMO }
@Test
public void onRedLinePromotionListOriginalPriceTest() {
testPromoState = "ORIGINAL";
testPrices.put("Product_A", 1.00);
testPrices.put("Product_B", 2.00);
testPrices.put("Product_C", 3.00);
expectedPrices = testPrices;
expectedGoodsMap.put(TestClassForItems.ITEMS.ORIGINAL, testPrices);
assertSame(expectedGoodsMap, TestClass.getPromotionItems(TestClassForItems.ITEMS.ORIGINAL,testPrices));
}
由于从 main 实例化所有必要的属性以运行我的 Junit 测试,返回相同的字符串结果但不同的对象使用情况。
【问题讨论】:
-
不要使用原始类型。
-
@shmosel 进行了编辑,现在尝试编译,看看你的想法。
-
我不确定你改变了什么,但
iterator、keys和map都在使用原始类型。 -
这里的语义很不清楚;您显然不想要可用的
EnumMap复制构造函数,但这似乎是在子图中发生键冲突的情况下随机选择最终值。 -
你不应该在这里发布你的测试代码吗?