断言可迭代的每个元素都匹配给定匹配器的惯用Hamcrest模式是什么?
问题内容:
检查以下代码段:
assertThat(
Arrays.asList("1x", "2x", "3x", "4z"),
not(hasItem(not(endsWith("x"))))
);
这断言该列表没有不以“ x”结尾的元素。当然,这是双重否定的说法,即列表的所有元素均以“ x”结尾。
另请注意,该代码段将引发:
java.lang.AssertionError:
Expected: not a collection containing not a string ending with "x"
got: <[1x, 2x, 3x, 4z]>
这将列出整个列表,而不只是不以“ x”结尾的元素。
有没有一种惯用的方式:
- 断言每个元素均以“ x”结尾(没有双负数)
- 断言错误时,仅列出不以“ x”结尾的那些元素
问题答案:
David Harkness提供的匹配器为 预期的部件 产生了很好的信息。但是, 实际零件
的消息还取决于assertThat
您使用哪种方法:
JUnit (org.junit.Assert.assertThat
)中的一个产生您提供的输出。
- 与
not(hasItem(not(...)))
匹配器:
java.lang.AssertionError:
Expected: not a collection containing not a string ending with "x"
got: <[1x, 2x, 3x, 4z]>
- 与
everyItem(...)
匹配器:
java.lang.AssertionError:
Expected: every item is a string ending with "x"
got: <[1x, 2x, 3x, 4z]>
Hamcrest (org.hamcrest.MatcherAssert.assertThat
)中的一个产生David给出的输出:
- 与
not(hasItem(not(...)))
匹配器:
java.lang.AssertionError:
Expected: not a collection containing not a string ending with "x"
but: was <[1x, 2x, 3x, 4z]>
- 与
everyItem(...)
匹配器:
java.lang.AssertionError:
Expected: every item is a string ending with "x"
but: an item was "4z"
我自己对Hamcrest断言的实验表明,“
but”部分经常令人困惑,具体取决于如何正确组合多个匹配器以及哪个匹配器首先失败,因此我仍然坚持使用JUnit断言,在该断言中我非常清楚将会在“获得”部分看到。