在使用JUnit / hamcrest进行单元测试时,是否存在特定的api来检查集合的大小。
目前我在做 -
Set<String> result = program.getCollection("inputdata");
assertThat(3, is(result.size()) );
以上是否可以接受,或者我应该使用iterableWithSize
,如下所示
assertThat(result, iterableWithSize(3));
标准方式应该是什么,或两种方法都可以。
答案 0 :(得分:3)
assertThat
的方法签名是:
<T> void assertThat(T actual, Matcher<? super T> matcher)
其中:
actual
是要比较的计算值matcher
是一个由{@link Matcher}构建的表达式,用于指定允许值因此,它的目的是阅读:
assert that this computed value matches that expected value
鉴于此,你问题中的断言:
Set<String> result = program.getCollection("inputdata");
assertThat(3, is(result.size()) );
应表示为:
assertThat(result.size(), is(3));
这是一个微妙的差异,但它更符合assertThat
的签名和Hamcrest匹配器的规范。
问题的其余部分涉及您是应该使用is
还是iterableWithSize
。以下所有断言都是(a)功能等同和(b)非常易读(恕我直言)。
assertThat(result.size(), is(3));
assertThat(result, iterableOfSize(3));
assertThat(result, hasSize(3));
没有令人信服的理由(主观意见除外)选择其他任何一个。我建议选择一种方法并始终如一地使用它,因为一致性原则&#39;应该比这里的正确性更受青睐,因为它们都是同样正确的。
答案 1 :(得分:2)
你的两种方法都是正确的,这只是一个品味问题,所以你可以选择你最喜欢的方式
引用iterableWithSize文档:
iterableWithSize(int size) 为Iterables创建一个匹配器,当对检查的Iterable进行单次传递产生一个等于指定大小参数的项目数时匹配
我个人会使用简单的assertEquals
:
assertEquals(3, result.size());
Hamcrest提供了更多的自然可读性,所以(我还没有尝试过)但我想你可以使用:
assertThat(result, is(iterableWithSize(3)));