Java I';我尝试使用Junit测试方法返回以下结构的Map对象:Map<;列表<;int[]>>;,Enum>;福。正确的方法是什么?

Java I';我尝试使用Junit测试方法返回以下结构的Map对象:Map<;列表<;int[]>>;,Enum>;福。正确的方法是什么?,java,Java,问题是,Junit将这些映射结果作为对象实例进行比较,因此始终无法通过测试,即使列表中包含正确的int数组和正确的Enum。 我的代码是这样的smth,我希望断言返回true Logic <Map<List<int[]>, Enum>> logic = new FooLogic(2, field, new StandardRules(PlaceHolders.getPlaceHolders())); Map<List<int[]>, Enum

问题是,Junit将这些映射结果作为对象实例进行比较,因此始终无法通过测试,即使列表中包含正确的int数组和正确的Enum。 我的代码是这样的smth,我希望断言返回true

Logic <Map<List<int[]>, Enum>> logic = new FooLogic(2, field, new StandardRules(PlaceHolders.getPlaceHolders()));
Map<List<int[]>, Enum> freeCells = logic.executeLogic();
Map<List<int[]>, Enum> expected = new LinkedHashMap<>();
expected.put(new ArrayList<>(List.of(new int[]{0, 0}, new int[]{0, 1})), Directions.EAST);
expected.put(new ArrayList<>(List.of(new int[]{0, 1}, new int[]{0, 0})), Directions.WEST);
Assert.assertThat(freeCells, Is.is(expected));
Logic Logic=new-foulogic(2,字段,新的标准规则(PlaceHolders.getPlaceHolders());
Map freeCells=logic.executeLogic();
预期映射=新LinkedHashMap();
expected.put(newarraylist(List.of(newint[]{0,0},newint[]{0,1})),Directions.EAST;
expected.put(newarraylist(List.of(newint[]{0,1},newint[]{0,0})),Directions.WEST;
Assert.assertThat(freeCells,Is.Is(预期));

问题在于
ArrayList
AbstractList
更准确地说)使用
equals
来比较元素,而数组不覆盖
equals
。所以
assertTrue(newint[]{0,0}.equals(newint[]{0,0}))失败,并且
断言(Lists.of(new int[]{0,0}),is(Lists.of(new int[]{0,0}))

使用数组(或数组列表)作为
映射
键是个坏主意,因为大多数映射也使用
equals
,因此不仅很难测试该方法的结果,而且在生产中也很难使用它:

int[] key = {0};
Map<int[], String> map = Maps.of(new Pair<>(key, "value"));
assertThat(map.get(key), is("value")); // passes
assertThat(map.get(new int[]{0}), is("value")); // fails
int[]键={0};
Map Map=Maps.of(新的一对(键,“值”);
资产(map.get(key)为(“值”);//通行证
assertThat(map.get(newint[]{0})是(“value”);//失败
为了解决这个问题,我建议将
Map
替换为
Map>>entries=freeCells.entrySet();

IteratorHx很多。我终于明白了!
List<Integer> key = Lists.of(1);
Map<List<Integer>, String> map = Maps.of(new Pair<>(key, "value"));
assertThat(map.get(key), is("value")); // passes
assertThat(map.get(Lists.of(1)), is("value")); // passes
Set<Entry<List<int[]>, Enum<?>>> entries = freeCells.entrySet();
Iterator<Entry<List<int[]>, Enum<?>>> entryIterator = entries.iterator();
assertEntryEquals(entryIterator.next(), Lists.of(new int[]{0, 0}, new int[]{0, 1}), Directions.EAST);
assertEntryEquals(entryIterator.next(), Lists.of(new int[]{0, 1}, new int[]{0, 0}), Directions.WEST);
assertFalse(entryIterator.hasNext());
private static void assertEntryEquals(Entry<List<int[]>, Enum<?>> entry, List<int[]> key, Enum<?> value) {
    assertThat(entry.getValue(), is(value));
    Iterator<int[]> original = entry.getKey().iterator();
    for (int[] expected : key) assertArrayEquals(original.next(), expected);
    assertFalse(original.hasNext());
}