单元测试断言TreeMap中的对象的顺序是否正确?

时间:2016-08-22 10:48:17

标签: java unit-testing junit classcastexception treemap

我正在尝试编写一个Junit测试来断言我TreeMap中的对象是正确的顺序

我该怎么办?

我正在尝试执行以下操作:

assertEquals(treeMapFromMethod.get(0), ValueThatShouldBeFirstEntryInTreeMap);

但我收到错误

"java.lang.ClassCastException: java.lang.Integer cannot be cast to MyObJect"

此错误与上面的行相关。

我该如何解决这个/有更好的方法来测试吗?

1 个答案:

答案 0 :(得分:1)

如果您使用Hamcrest,您可以使用contains匹配器轻松完成此操作:

TreeMap<String, Integer> map = new TreeMap<>();
map.put("one", 1);
map.put("two", 2);
map.put("three", 3);

Assert.assertThat(map.keySet(), Matchers.contains("one", "three", "two"));

contains匹配器检查给定集合是否具有相同的长度并且包含相同顺序的给定项目。

相关问题