给定集合:
Collection<MyObject> expected = Collections.singletonList(new MyObject);
Collection<MyObject> actual = Collections.unmodifiableCollection(new ArrayList<>(expected));
但是断言两者都是
assertSame(expected, actual);
我看到断言错误:
java.lang.AssertionError:
expected same:<[com.flyeralarm.autopattern.algorithm.JobTransform@8807e25]>
was not: <[com.flyeralarm.autopattern.algorithm.JobTransform@8807e25]>
Expected :[com.flyeralarm.autopattern.algorithm.JobTransform@8807e25]
Actual :[com.flyeralarm.autopattern.algorithm.JobTransform@8807e25]
但预期和实际都向我展示了相同的 hashCode。为什么测试会失败?
更新
在尝试使用 Assert#asserEquals 运行测试后,我发现 expected 是一个 SingletonList,它绝不会等于实际的 UnmodifiableCollection。因此我有另一个问题:比较这两种类型的集合的最佳方法是什么。
最佳答案
比较列表的一种方法是将它们转换为数组,然后将它们与 assertArrayEquals 进行比较:
assertArrayEquals(expected.toArray(), actual.toArray());
要使其正常工作,列表中的项目必须提供正确的 equals()
方法。
关于java - 使用 JUnit 将 Collection#unmodifiableCollection 与 Java 中的 Collection#singletonList 进行比较,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38431435/