pol*_*nts 25 java idioms hamcrest
检查以下代码段:
assertThat(
Arrays.asList("1x", "2x", "3x", "4z"),
not(hasItem(not(endsWith("x"))))
);
Run Code Online (Sandbox Code Playgroud)
这断言列表没有不以"x"结尾的元素.当然,这是表示列表中所有元素都以"x"结尾的双重否定方式.
另请注意,该片段会引发:
java.lang.AssertionError:
Expected: not a collection containing not a string ending with "x"
got: <[1x, 2x, 3x, 4z]>
Run Code Online (Sandbox Code Playgroud)
这列出了整个列表,而不仅仅是不以"x"结尾的元素.
那么有一种惯用的方式:
Dav*_*ess 23
您正在寻找everyItem():
assertThat(
Arrays.asList("1x", "2x", "3x", "4z"),
everyItem(endsWith("x"))
);
Run Code Online (Sandbox Code Playgroud)
这会产生一个很好的失败消息:
Expected: every item is a string ending with "x"
but: an item was "4z"
Run Code Online (Sandbox Code Playgroud)
Chr*_*rau 17
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]>
Run Code Online (Sandbox Code Playgroud)使用everyItem(...)匹配器:
java.lang.AssertionError:
Expected: every item is a string ending with "x"
got: <[1x, 2x, 3x, 4z]>
Run Code Online (Sandbox Code Playgroud)来自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]>
Run Code Online (Sandbox Code Playgroud)使用everyItem(...)匹配器:
java.lang.AssertionError:
Expected: every item is a string ending with "x"
but: an item was "4z"
Run Code Online (Sandbox Code Playgroud)我自己对Hamcrest声明的实验表明,"但是"部分经常令人困惑,这取决于多个匹配器的组合方式以及哪一个首先失败,因此我仍然坚持使用JUnit断言,我完全知道我在哪里我会在"得到"的部分看到.