我想知道人们如何对“期望”的集合进行单元测试和断言,以确保它与“实际”集合相同/类似(顺序不重要)。
为了执行这个断言,我编写了一个简单的assert API:
public void assertCollection(Collection<?> expectedCollection, Collection<?> actualCollection) {
assertNotNull(expectedCollection);
assertNotNull(actualCollection);
assertEquals(expectedCollection.size(), actualCollection.size());
assertTrue(expectedCollection.containsAll(actualCollection));
assertTrue(actualCollection.containsAll(expectedCollection));
}
它有效。如果我只断言一堆整数或字符串,那么这很简单。但是如果我要断言一组Hibernate域,那么这可能会非常麻烦。例如,collection.containsAll(..)依赖于equals(..)执行检查,但我总是覆盖我的Hibernate域中的equals(..),只检查业务键(这是Hibernate网站上规定的最佳实践),而不是该域的所有字段。当然,只检查业务键是有意义的,但有时我确实希望确保所有字段都正确,而不仅仅是业务键(例如,新的数据输入记录)。所以,在这种情况下,我不能搞乱domain.equals(..),似乎我需要为仅进行单元测试目的而实现一些比较器,而不是依赖于collection.containsAll(..)。
这里是否有一些可以利用的测试库?您如何测试您的集合?
谢谢。
CombinableMatcher
中的(org.hamcrest.Matcher<? super java.lang.Iterable<java.util.Collection<org.hamcrest.Matcher<org.bitbucket.artbugorski.brainfuj.interpreter.InterpreterTest.Foo>>>>)
无法应用于(org.hamcrest.Matcher<capture<? super java.util.Collection<? extends java.lang.Object>>>)
。 - SledSamePropertyValueAs
,但是testBeans()
方法在junit4.11和hamcrest1.3中已经失效。both..and
在and
上出现问题;hasItems(..)
在assertThat
上也出现问题。 - djeikyberror: reference to hasItems is ambiguous, both method <T#1>hasItems(T#1...) in IsCollectionContaining and method <T#2>hasItems(T#2...) in JUnitMatchers match
的错误提示? - Matthew Wise